[rspec-users] mocking named_scope utilization

Fernando Perez lists at ruby-forum.com
Tue Nov 4 18:29:57 EST 2008


Here you go:

It's not easy to test for the following named_scopes:
--
Thing.method1(@current_user).method2.method3 :page =>
params[:page]
--

I tried:
--
Thing.should_receive(:method1)..
Thing.should_receive(:method2)..
Thing.should_receive(:method3)
--
But testing for these three method calls didn't work. I have an error as 
"could not evaluate nil.method2". That's because of the way Rails treats 
chained named_scopes, each method only exists in the context of its 
surrounding scopes. method1 doesn't anything when followed by method2, 
it's because rails dynamically creates a method that would be called 
something like method1_and_method2 if you know what I'm sayin'.

Therefore a workaround is to define an instance method:
--
class Thing
  def self.method1_and_method2(arg)
    method1(arg).method2
  end
end
--

Then in the controller, you would call: Thing.method1_and_method2

Now you can spec that easily with:
--
Thing.should_receive(:method1_and_method2).with(...)
--

And it works.
-- 
Posted via http://www.ruby-forum.com/.


More information about the rspec-users mailing list