【问题标题】:Rspec: stubbing controller methods ineffective (before_filter, private)Rspec:存根控制器方法无效(before_filter,私有)
【发布时间】:2013-08-05 16:36:57
【问题描述】:

即使在阅读了几十个线程和博客文章之后,我仍然无法存根控制器方法,所以这是我的情况:

我的控制器:app/controllers/my_controller.rb

class MyController < ApplicationController
  before_filter :my_private_method, only:[:new]

  # ...

  private

  # This should be stubbed and not fire
  def my_private_method
    binding.pry
    redirect_to '/failure.html'
  end
end

我的规范:spec/controllers/my_spec.rb

describe MyController do
  before :each do   
    controller.stub!(:my_private_method).and_return(true)
  end

  it 'should load' do
    binding.pry
    visit new_my_path
    response.status.should == 200
  end
end

我的系统:

ruby 1.9.3p448(2013-06-27 修订版 41675)[x86_64-linux]

Rails 3.2.13

有什么帮助吗?

顺便说一句,我发现当我在it 'should load' 块中使用binding.pry 检查controller.object_id 时,我得到一个不同 object_id,而不是在my_private_method 中检查self.object_id

【问题讨论】:

    标签: ruby-on-rails rspec stub


    【解决方案1】:

    我认为,您的“偶然”评论与这里发生的事情非常相关。

    我相信您规范中的 controller 变量与 RSpec 在您将 MyController 传递给 describe 时所做的隐式 MyController.new 相关联。但是,MyController 的实例与您访问 new_my_path 时由 Rails 创建的实例不同。

    我相信你可以使用MyController.any_instance.stub在这里做你想做的事情。

    【讨论】:

    • 我在删除控制器(Rails 应用程序)中调用的模型方法时遇到问题。无论我是在实例级别还是类级别存根,都会调用存根方法并在测试时执行其中的代码。我是否也可能有两个不同实例的类似情况?这是测试 Rails 控制器时的常见问题吗?
    • 如何确定这一点,即在控制器和 rspec 测试中打印 object_id?
    • 您当然可以打印 object_ids(或者只打印对象,因为它们包含对象地址,这也是唯一的),但是如果您使用 any_instance 存根,我不明白为什么您的实际代码仍会被调用。坦率地说,我没有在 Rails 中做过任何控制器测试,所以我无法从经验中回答这是否是一个常见问题。
    • 我也试过MyController.any_instance.stub。没有更好的效果。顺便说一句,MyController.any_instance.stub!(带有感叹号)引发RuntimeError: stub! is not supported on any_instance. Use stub instead.
    • @JellicleCat,知道它不能回答您的问题,但是您是否考虑过/尝试过relishapp.com/rspec/rspec-rails/docs/controller-specs 中描述的方法?我会就最初的问题回复你。
    【解决方案2】:

    解决方法是在规范中使用visit以外的方法。显然,visit 仅用于功能规范。而是使用getpost 等。

    【讨论】:

    • 这与 relishapp.com/rspec/rspec-rails/docs/controller-specs 一致,但没有解释为什么 any_instance_of 方法不起作用。
    • 我完全同意。不过,这是我的经验。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    相关资源
    最近更新 更多