【问题标题】:Why can't I access the controller object in RSpec when testing a controller?为什么我在测试控制器时无法访问 RSpec 中的控制器对象?
【发布时间】:2009-05-27 14:45:18
【问题描述】:

我正在使用 rspec-rails,版本 1.2.6。在控制器测试中

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

从所有示例中,访问控制器变量应该可以工作,但事实并非如此。是什么赋予了?如何在被测控制器中模拟或存根方法?

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-on-rails-plugins


    【解决方案1】:

    尝试使用@controller 而不是控制器

    【讨论】:

      【解决方案2】:

      删除之前块中的 :all 可以解决问题。不过不知道为什么。

      before do
      ...
      end
      

      是你需要的。

      【讨论】:

      • 这是因为 before(:all) 块在系统启动时运行一次,而 before()(实际上是 before(:each) ) 块在每次测试之前运行,并且发生在 after 任何在外部上下文中定义的 before(:each) 块。
      【解决方案3】:

      如果您在 before(:all) 块中需要 controller,请致电 setup_controller_request_and_response

      【讨论】:

        【解决方案4】:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多