Reputation: 116
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?
Upvotes: 2
Views: 2906
Reputation: 323
PS: This behavior should be fixed in recent versions of RSpec.
See a running example from RSpec v.2.14:
require "spec_helper"
RSpec.configure {|c| c.before { expect(controller).not_to be_nil }}
describe WidgetsController do
describe "GET index" do
it "doesn't matter" do
end
end
end
Upvotes: 0
Reputation: 4333
If you need controller
in a before(:all)
block, call setup_controller_request_and_response
.
Upvotes: 1
Reputation: 116
Remove the :all in the before block fixes the issue. Not sure why, though.
before do
...
end
is what you need.
Upvotes: 2