When testing Rails applications, two of the most significant performance bottlenecks are accessing the database and loading Rails itself. RSpec Mocks and other mocking frameworks give us the tools to avoid these bottlenecks by allowing us to mock our Rails models, but doing so can be tedious.

1. ActiveMocker

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:

2.1 Installation

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

References

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.
https://github.com/zeisler/active_mocker

Mocking ActiveRecord with ActiveMocker :: Envy
https://web.archive.org/web/20150511052653/http://madewithenvy.com/ecosystem/articles/2015/mocking-activerecord-with-activemocker/

打赏

Leave a Reply

Your email address will not be published. Required fields are marked *