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

Mat*_*ham 63 ruby rspec ruby-on-rails capybara

我需要current_user在Rspec/capybara请求规范中存根方法的响应.该方法在ApplicationControllerhelper_method中定义并使用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
Run Code Online (Sandbox Code Playgroud)

也不工作:

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
Run Code Online (Sandbox Code Playgroud)

fes*_*s . 59

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

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

ApplicationController.any_instance.stub(:current_user)

  • 这仍适用于Rspec 3但提供弃用警告.这是新语法:`allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(your_test_user)` (29认同)

jef*_*unt 14

以下是基本形式的几个示例.

controller.stub(:action_name).and_raise([some error])
controller.stub(:action_name).and_return([some value])
Run Code Online (Sandbox Code Playgroud)

在您的特定情况下,我认为正确的形式是:

controller.stub(:current_user).and_return([your user object/id])
Run Code Online (Sandbox Code Playgroud)

这是我工作的项目的完整工作示例:

describe PortalsController do

  it "if an ActionController::InvalidAuthenticityToken is raised the user should be redirected to login" do
    controller.stub(:index).and_raise(ActionController::InvalidAuthenticityToken)
    get :index
    flash[:notice].should eql("Your session has expired.")
    response.should redirect_to(portals_path)
  end

end
Run Code Online (Sandbox Code Playgroud)

为了解释我的完整示例,基本上它的作用是验证当ActionController::InvalidAuthenticityToken应用程序中的任何地方出现错误时,会出现一条flash消息,并且用户被重定向到该portals_controller#index操作.您可以使用这些表单来存根并返回特定值,测试引发的给定错误的实例等.您可以使用多种.stub(:action_name).and_[do_something_interesting]()方法.


更新(在您添加代码之后):根据我的评论,更改您的代码,使其显示为:

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
Run Code Online (Sandbox Code Playgroud)