2009-05-27 77 views
1

我正在使用rspec-rails,版本1.2.6。在控制器测试为什么在测试控制器时无法访问RSpec中的控制器对象?

describe WebsController do ... 

我似乎没有访问控制器对象为了存根方法。例如,以下将不起作用:

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

我得到的警告一样

An expectation of :feed_from_params was set on nil. 

,并发射了调试会话从规范只是方法模拟前告诉就行了,我得到的如下:

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

从所有的例子,访问控制器变量应该工作,但它不。是什么赋予了?我怎样才能在被测试的控制器中模拟或存根方法?

回答

2

删除:所有的块修复该问题之前。不知道为什么,但。

before do 
... 
end 

是你所需要的。

+2

这样做的原因是,前(:所有)块在系统启动时运行_once_,而前()(这是一个真正的前(:each))块在每次测试之前运行,并且在_after_之前发生(:each)在外部上下文中定义的块。 – 2009-06-12 15:51:35

3

尝试使用@Controller而非控制器

1

如果您需要controllerbefore(:all)区块中,请致电setup_controller_request_and_response

0

PS:此行为应该在最新版本的RSpec中修复。

从RSpec的v.2.14看到一个running example

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