我需要在Rspec/capybara请求规范中存根current_user
方法的响应。该方法是在ApplicationController
中定义的,并且使用helper_method。该方法应该只返回一个用户id。在测试中,我希望这个方法每次都返回相同的用户id。
或者,我可以通过在规范中设置session[:user_id]
(这是current_user
返回的内容)来解决我的问题……但这似乎也行不通。
这两种情况都有可能吗?
编辑:
这是我得到的(它不工作。它只运行正常的current_user方法)。
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
发布于 2012-08-30 05:27:11
skalee似乎在评论中提供了正确的答案。
如果您尝试存根的方法是一个实例方法(很可能),而不是一个类方法,那么您需要使用:
ApplicationController.any_instance.stub(:current_user)
发布于 2012-10-14 09:01:55
这对我很有效,并为我提供了一个在测试中使用的@current_user
变量。
我有一个助手,看起来像这样:
def bypass_authentication
current_user = FactoryGirl.create(:user)
ApplicationController.send(:alias_method, :old_current_user, :current_user)
ApplicationController.send(:define_method, :current_user) do
current_user
end
@current_user = current_user
end
def restore_authentication
ApplicationController.send(:alias_method, :current_user, :old_current_user)
end
然后在我的请求规范中,我调用:
before(:each){bypass_authentication}
after(:each){restore_authentication}
发布于 2013-11-07 10:14:28
对于任何碰巧需要存根设置ivar的应用程序控制器方法(并被无休止地抱怨为什么不应该这样做)的人来说,这里有一种有效的方法,带有大约2013年10月的Rspec风格。
before(:each) do
campaign = Campaign.create!
ApplicationController.any_instance.stub(:load_campaign_singleton)
controller.instance_eval{@campaign = campaign}
@campaign = campaign
end
它将方法存根为不做任何事情,并在rspec的控制器实例上设置ivar,并将其作为@campaign提供给测试。
https://stackoverflow.com/questions/7448974
复制相似问题