I am using Ruby on Rails 3.1.0 and the rspec-rails 2 gem. I am testing my controller code (BTW: I am newbie to rspec) and I would like to make possible that a class object instance returns a predefined value. That is, in my controller I have:
def create
...
if @current_user.has_authorization?
...
else
...
end
end
In order to test the “else part” of the if statement I would like to make possible that (for the current spec example that I am working on – read below for a sample implementation) the @current_user.has_authorization? returns false.
How can I make that?
I tried the following in my spec file, but it seems do not work as expected:
it "should have no authorization" do
@current_user.stub(:has_authorization?).and_return(false)
# I also tried the following and it still doesn't work
# @current_user.should_receive(:has_authorization?).and_return(false)
post :create
...
end
@current_userin the context of your rspec test is not the same as@current_userin the context of your controller. One is an instance variable, in the instance of your controller class that Rails is running. The other is an instance variable in your rspec test.You aren’t supposed to poke at your user variable, but rather need to make it so Rails finds a User supplied by the test framework. Take a look at this example.