如何在请求规范中存根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屋!