Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Testing named scopes with RSpec

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

like image 731
andrykonchin Avatar asked Jun 26 '11 17:06

andrykonchin


1 Answers

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.

like image 123
Joost Baaij Avatar answered Sep 24 '22 01:09

Joost Baaij