Reputation: 7359
Imagine I have routes like this:
resource :users do
resource :projects
do
project.rb
...
belongs_to :users
...
user.rb
...
has_many :projects
...
If I wanted to create rspec tests for Project, would I test Project by itself without User? In theory there would never be a Project without a User, since a User creates a Project. Something like this:
project_spec.rb
...
it "is created by a user"
...
or
user_spec.rb
...
it "create a project"
...
And if I wanted to make a test for User creating Project would I do it in the user_spec, or in project_spec? Or both?
Upvotes: 0
Views: 181
Reputation: 1644
I usually use mocks for isolation and speed. These specs test only up to the boundary of the User object, and do not hit the database or do anything real with the Project model. They test behavior not state.
(the following uses RSpec 2.11 features)
describe User do
let(:project){ mock_model(Project) }
subject(:user){ User.new(:project => project) }
it "does something with a project" do
project.should_receive(:some_method_call).and_return(:a_value)
user.do_something
end
end
describe User do
let(:fake_project_class) { Class.new }
let(:project){ double('a_project') }
subject(:user){ User.new }
before(:each) do
stub_const("Project", fake_project_class)
end
it "creates a project" do
Project.should_receive(:new).and_return(project)
user.make_me_a_project!
end
end
Upvotes: 1