[rspec-users] Stubbing controller methods vs model methods

Chris Olsen lists at ruby-forum.com
Tue Jan 29 20:23:02 EST 2008


I had an error that I couldn't figure out, then when writing up a
question for the forum I figured it out.  The thing is I don't
understand why the change that was made works and why what existed
before didn't.

Here is the initial post when I had the error:
----------------------------------
In the controllers/application.rb file

I have a method that finds the account based on the subdomain.  This
method is stubbed out for the tests.
def find_account
    @account = Account.for(request.host.split(".").first)  #TODO: find
out why request.subdomains returns []
end

In my controller tests I would like to stub this method.  So I created a
method within the authenticated_test_helper.rb (I am using RESTful
Authentication plugin)

  def login_with_account(account)  # <===
    # User
    current_user = mock_model(User)
    controller.stub!(:current_user).and_return(current_user)

    # User's account
    account.stub!(:users).and_return([current_user])
    current_user.stub!(:account).and_return(account)

    # Application methods
    controller.stub!(:logged_in?).and_return(true)
    controller.stub!(:authorized?).and_return(true)
    controller.stub!(:find_account).and_return(account)  # <===
find_account stubbed out
  end

Now in the before methods of my controller specs I have:
  before :each do
    account = mock_model(Account, :subdomain => "test2")
    login_with_account(account)   # <===
  end

The place that keeps throwing up is the controller's index method

def index
   @users = @account.users
end

where the error message is:
NoMethodError in 'Admin::UsersController GET, test2.localhost/users
should validate the user'
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.users

*** The fix
I found that if I stubbed out the Account.for method instead of the
controller helper method it then worked.
+>> Account.stub!(:for).and_return(account)
->> controller.stub!(:find_account).and_return(account)  # removed

As a reminder here is the find_account method
def find_account
    @account = Account.for(request.host.split(".").first)
end

Am I not stubbing the controller methods properly?  That method is in
the ApplicationController so it would be inherited and therefore
accessible through the "controller" reference right?

Thanks for the help.

BTW has any heard about the Pragmatic Rspec book?  I swear I check the
pragprog.com site everyday for that book :)
-- 
Posted via http://www.ruby-forum.com/.


More information about the rspec-users mailing list