0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.