如何在请求规范中存根 ApplicationController 方法 [英] How to stub ApplicationController method in request spec
问题描述
我需要在 Rspec/capybara 请求规范中存根 current_user
方法的响应.该方法在 ApplicationController
中定义并使用 helper_method.该方法应该简单地返回一个用户 ID.在测试中,我希望此方法每次都返回相同的用户 ID.
I am needing to stub the response of a current_user
method in an Rspec/capybara request spec. The method is defined in ApplicationController
and is using helper_method. The method should simply return a user id. Within the test, I'd like this method to return the same user id each time.
或者,我可以通过在规范中设置 session[:user_id]
来解决我的问题(这是 current_user
返回的内容)......但这似乎不是要么工作.
Alternatively, I could fix my problem by setting session[:user_id]
in the spec (which is what current_user
returns)... but that doesn't seem to work either.
这两种都有可能吗?
这是我得到的(它不起作用.它只是运行普通的 current_user 方法).
Here is what I've got (it is not working. It just runs the normal current_user method).
require 'spec_helper'
describe "Login" do
before(:each) do
ApplicationController.stub(:current_user).and_return(User.first)
end
it "logs in" do
visit '/'
page.should have_content("Hey there user!")
end
end
也不起作用:
require 'spec_helper'
describe "Login" do
before(:each) do
@mock_controller = mock("ApplicationController")
@mock_controller.stub(:current_user).and_return(User.first)
end
it "logs in" do
visit '/'
page.should have_content("Hey there user!")
end
end
推荐答案
skalee 似乎在评论中提供了正确答案.
skalee seems to have provided the correct answer in the comment.
如果您尝试存根的方法是实例方法(最有可能)而不是类方法,那么您需要使用:
If the method you're trying to stub is an instance method (most likely) and not a class method then you need use:
ApplicationController.any_instance.stub(:current_user)
这篇关于如何在请求规范中存根 ApplicationController 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!