I am new to testing Rails web applications and RSpec. I work with legacy code and need to add tests. So what is the best way to test finders and named scopes with RSpec?
I find in Google a few approaches but they are not ideal. For example:
http://paulsturgess.co.uk/articles/show/93-using-rspec-to-test-a-named_scope-in-ruby-on-rails
it "excludes users that are not active" do @user = Factory(:user, :active => false) User.active.should_not include(@user) end
or
http://h1labs.com/notebook/2008/8/21/testing-named-scope-with-rspec
it "should have a published named scope that returns ..." do Post.published.proxy_options.should == {:conditions => {:published => true}} end
I find best approach (IMHO) in "Rail Test Prescriptions":
should_match_find_method :active_only { :active == true }
where should_match_find_method
custom helper method
The creator of RSpec has recently blogged he thinks Validations are behavior, associations are structure. In other words he finds that associations (and scopes) should not nessesarily be tested directly. Tests for these will follow from the behavior you want.
In other words, current wisdom is that there is no need to test each scope directly, since you will cover these associations by testing the behavior of your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With