|
|
|
|
|
by latortuga
5000 days ago
|
|
This would've been good when I was just starting with RSpec. A couple things I'd like to add: Mock or not to Mock
Mock and stub relentlessly. Ensure that the object you're testing the behavior of sends the right messages to its collaborators but put the tests for those messages in the unit test for the collaborator. This keeps your tests isolated and fast. As long as you adhere to "Tell, Don't Ask" you should simply be able to assert that your method is sending messages to other objects without relying on the behavior that those methods perform. Create only the data you need
describe "User"
describe ".top" do
before { 3.times { Factory(:user) } }
it { User.top(2).should have(2).item }
end
end
The author advocates not creating dozens of objects but why make any at all? This seems like a place where setting expectations is a better course of action. There's no reason to test ActiveRecord query methods like this - just assert that the filters that you want are being set by the method and call it. I usually do something like this (using rspec-mocks): subject.should_receive(:popular).and_return(subject)
subject.should_receive(:by_create_date).and_return(subject)
...
This lets you know that the class method is performing the filtering you want without actually fetching data from the db. Much like validations, this is the kind of thing you can rely on either the Rails team or the db adapter writers to get the actual filtering right without having to test this over and over in your app. Having your unit tests (business logic!) actually hit your persistence layer like this is the kind of thing that makes test suites slow! |
|
No, writing good tests keeps your test isolated and fast. Creating lots of mock objects distracts you from writing good tests, because what you're testing is your ability to 1) write mock objects that conform to the ad hoc interfaces you've produced and 2) maintain those mock objects when those ad hoc interfaces change.
If you want to know if your code works, you still have to test if it all works together.