Search code examples
ruby-on-railsrubyrspecruby-on-rails-plugins

Why can't I access the controller object in RSpec when testing a controller?


I'm using rspec-rails, version 1.2.6. In a controller test

describe WebsController do ...

I don't seem to have access to the controller object in order to stub methods. For example, the following won't work:

  before :all do
    @feed = mock_model(Feed)
    controller.should_receive(:feed_from_params).and_return @feed    
  end

I get warnings like

An expectation of :feed_from_params was set on nil. 

and firing up a debug session from the spec tells on the line just before the method mock, I get the following:

(rdb:1) self.respond_to? :controller
true
(rdb:1) controller
nil

From all the examples, accessing the controller variable should work, but it doesn't. What gives? How can I mock or stub methods in a controller under test?


Solution

  • Remove the :all in the before block fixes the issue. Not sure why, though.

    before do
    ...
    end
    

    is what you need.