ActiveMocker is a gem created by Dustin Zeisler that allows us to “Generate mocks from ActiveRecord models for unit tests that run fast because they don’t need to load Rails or a database”.
Creates stub classes from any ActiveRecord model.
By using stubs in your tests you don’t need to load Rails or the database, sometimes resulting in a 10x speed improvement.
ActiveMocker analyzes the methods and database columns to generate a Ruby class file.
The stub file can be run standalone and comes included with many useful parts of ActiveRecord.
Stubbed out methods contain their original argument signatures or ActiveMocker’s friendly code can be brought over in its entirety.
Mocks are regenerated when the schema is modified so your mocks won’t go stale, preventing the case where your unit tests pass but production code fails.
2. How it Works
Each time we modify our schema, ActiveMocker generates a new mock for each of our models in spec/mocks. ActiveMocker supports much of the ActiveRecord interface, including methods for creating, querying, and destroying records, as well as associations. The key difference is that instead of persisting and querying records from the database, it’s done in memory, which is much faster.
Using ActiveMocker is as simple as requiring the gem and adding the active_mocker:true tag:
Add this line to your application’s Gemfile:
group :development, :test do gem 'active_mocker' end
2.2 Using With Rspec, –tag active_mocker:true
describe 'Example', active_mocker:true do before do Person.create # stubbed for PersonMock.create end end
zeisler/active_mocker: Generate mocks from ActiveRecord models for unit tests that run fast because they don’t need to load Rails or a database.
Mocking ActiveRecord with ActiveMocker :: Envy