On 10/26/07, Steve <vertebrate at gmail.com>
wrote:> I have some finders in my models where I write some of the sql myself. I
> of course want to test these, but am not sure the best way. Should I just
> let them roll through to the db, and verify they return the correct
> objects based on the fixtures I load, or should I spec the actual query? I
> know that DB access is sort of frowned upon, but is this a situation where
> it is more or less acceptable? My spec looks something like this, but just
> feels funny because I''m essentially rewriting the query.
>
> describe User, ''when calling find_by_username'' do
> before(:each) do
> User.stub!(:find).and_return(nil)
> end
>
> it ''should convert the username to lowercase'' do
> uname = ''Joe''
> uname.should_receive(:downcase).and_return(''joe'')
> User.find_by_username(uname)
> end
>
> it ''should call find with custom options'' do
> User.should_receive(:find) do |a, b|
> a.should == :first
> b[:conditions][0].should == "lower(username) = :username"
> b[:conditions][1][:username].should == ''joe''
> end
> User.find_by_username(''Joe'')
> end
> end
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>
When I have custom queries I insert a couple records that should
match, and a couple that shouldn''t. Run the query and make sure the
results only include the ones that should match.
Another way is to write a story that calls that finder somewhere. I
haven''t found that to be particularly useful at this point, but I
think that''s the approach that David C prefers.
Pat