views:

268

answers:

2

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?

+2  A: 

Try using @controller rather than controller

tomafro
A: 

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

before do
...
end

is what you need.

Scott
The reason for this is that a before(:all) block is run _once_ at system startup, whereas a before() (which is really a before(:each)) block is run before each test, and happens _after_ any before(:each) blocks defined in an outer context.
James A. Rosen