即使在阅读了几十个主题和博客文章之后,我也没有找到控制器方法,所以这是我的情况:
我的控制器: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
有任何帮助吗?
顺便说一句,我发现当我使用binding.pry
检查controller.object_id
块中的it 'should load'
时,我得到的不同 object_id比检查时{{1}在self.object_id
。
答案 0 :(得分:2)
我认为你的“附带”评论与这里发生的事情非常相关。
我相信您的规范中的controller
变量与RSpec在您将MyController.new
传递给MyController
时完成的隐式describe
相关联。但是,MyController
的实例与您访问new_my_path
时由Rails创建的实例不同。
我相信你可以使用MyController.any_instance.stub
做你想做的事。
答案 1 :(得分:1)
解决方案是在规范中使用visit
以外的方法。显然,visit
仅适用于功能规格。相反,请使用get
或post
等