niedziela, 26 lutego 2012

How to proper test scopes (named scopes)


I just read few posts about "how to test named scopes". I'm asking - why should I use FactoryGirl and create tons of unnecessary objects just to test `order(:position).first`?!

How not to do this


require 'spec_helper'
describe Post do
context '#recent' do
it 'should return most recent post' do
_, post = [Factory(:post), Factory(:post)]
Post.recent.should == post
end
end
context '#for_user' do
it 'should return only posts created by given user' do
post1, post2, _ = [Factory(:post, user_id: 1), Factory(:post, user_id: 1), Factory(:post, user_id: 2)]
Post.for_user(1).should == [post1, post2]
end
end
end
view raw post_spec.rb hosted with ❤ by GitHub
We've just created .. let's count .. 5 objects and made 2 unnecessary db queries

How to do this


require 'spec_helper'
describe Post do
context '#recent' do
it 'should return most recent post' do
post = mock_model Post
Post.should_receive(:order).with('created_at DESC').and_return post
post.should_receive(:first).and_return post
Post.recent
end
end
context '#for_user' do
it 'should return only posts created by given user' do
post = mock_model Post
Post.should_receive(:where).with(user_id: 1)
Post.for_user 1
end
end
end
view raw post_spec.rb hosted with ❤ by GitHub
It's useless to test Rails (it's really proper tested). We need to spec messages that goes between objects and given parameters.

Brak komentarzy:

Prześlij komentarz