首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在请求规范中存根ApplicationController方法

如何在请求规范中存根ApplicationController方法
EN

Stack Overflow用户
提问于 2011-09-17 02:36:31
回答 5查看 39.6K关注 0票数 66

我需要在Rspec/capybara请求规范中存根current_user方法的响应。该方法是在ApplicationController中定义的,并且使用helper_method。该方法应该只返回一个用户id。在测试中,我希望这个方法每次都返回相同的用户id。

或者,我可以通过在规范中设置session[:user_id] (这是current_user返回的内容)来解决我的问题……但这似乎也行不通。

这两种情况都有可能吗?

编辑:

这是我得到的(它不工作。它只运行正常的current_user方法)。

代码语言:javascript
复制
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

同样不起作用:

代码语言:javascript
复制
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
EN

回答 5

Stack Overflow用户

发布于 2012-08-30 05:27:11

skalee似乎在评论中提供了正确的答案。

如果您尝试存根的方法是一个实例方法(很可能),而不是一个类方法,那么您需要使用:

ApplicationController.any_instance.stub(:current_user)

票数 61
EN

Stack Overflow用户

发布于 2012-10-14 09:01:55

这对我很有效,并为我提供了一个在测试中使用的@current_user变量。

我有一个助手,看起来像这样:

代码语言:javascript
复制
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

然后在我的请求规范中,我调用:

代码语言:javascript
复制
before(:each){bypass_authentication}
after(:each){restore_authentication}
票数 3
EN

Stack Overflow用户

发布于 2013-11-07 10:14:28

对于任何碰巧需要存根设置ivar的应用程序控制器方法(并被无休止地抱怨为什么不应该这样做)的人来说,这里有一种有效的方法,带有大约2013年10月的Rspec风格。

代码语言:javascript
复制
before(:each) do
  campaign = Campaign.create!
  ApplicationController.any_instance.stub(:load_campaign_singleton)
  controller.instance_eval{@campaign = campaign}
  @campaign = campaign
end

它将方法存根为不做任何事情,并在rspec的控制器实例上设置ivar,并将其作为@campaign提供给测试。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7448974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档