Stubbing ActiveRecord associations

mocking, rspec, ruby-on-rails, stubbing

Solution

If you don't want to create anything in the database you can do this:

employee = mock_model(Employee)
task = mock_model(Task, name: "Do that", employee: employee)

Keep in mind that you can't query them like that. It's roughly the same as building the object. If you ever want to do anything where you need to query actual data such as an integration test then you'll need use `create` to make stuff in the database. Or as one commenter pointed out, you can use FactoryGirl's methods to stub stuff out.

Problem

Say I have a Company which may contain many employees of type Employee may contain many tasks of type Task. ``` class Company < ActiveRecord::Base; has_many :employees; end class Employee < ActiveRecord::Base; belongs_to :company, has_many :tasks; end class Task < ActiveRecord::Base; belongs_to :employee; end ``` Using tools like FactoryGirl I may be tempted to create tasks using `FactoryGirl.create(:task)` forcing an employee and a company to be created as well. What I want to do is to create valid ActiveRecord objects but with their relationships stubbed out so as to make my tests faster. A solution I came up is to not use FactoryGirl and create the new objects using mock_model/stub_model to stub their associations. Example: ``` employee = mock_model(Employee) task = Task.create! name: "Do that", employee: employee ``` Am I doing it right? Thanks.

Original source