RSpec访问application_controller方法,例如'current_user'

时间:2010-09-15 19:10:36

标签: ruby-on-rails rspec rspec-rails

我正在尝试使用rspec在我的current_user(使用修改后的restful_authentication auth解决方案)上存根方法。我完全不确定如何在我的控制器规范中访问此方法。 current_user本身不起作用。我需要首先获得控制器吗?我该怎么做?

使用rails 2.3.5rspec 1.3.0rspec-rails 1.3.2

# my_controller_spec.rb
require 'spec_helper'

describe MyController do

  let(:foos){ # some array of foos }

  it "fetches foos of current user" do
    current_user.should_receive(:foos).and_return(foos)
    get :show
  end
end

可生产

NoMethodError in 'ChallengesController fetches foos of current user'
undefined method `current_user' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1::Subclass_1::Subclass_2::Subclass_2:0x7194b2f4>

4 个答案:

答案 0 :(得分:2)

rspec-rails为您提供了一个controller方法,可用于控制器示例。所以:

controller.stub!(:current_user).with(:foos).and_return(foos)

应该工作。

答案 1 :(得分:1)

怎么知道在哪里找current_user?这应该解决它:

subject.current_user.should_receive(:foos).and_return(foos)

答案 2 :(得分:0)

我并不完全熟悉restful_authentication,只是Authlogic和Devise,但它可能类似,因为current_user是一个控制器方法而不是一个对象,这就是为什么在它上面调用should_receive不是'按预期工作(您对current_user 返回的对象设置了期望值,但该方法无法在您期望的范围内访问。)

试试这个:

stub!(:current_user).and_return(foos)

答案 3 :(得分:0)

我读了这篇并稍微调整了一下。如果您只想将用户对象传入Rspec测试,可以使用:

  1. 首先,在rspec测试中创建一个用户对象。例如: (使用您需要或创建用户对象所需的任何属性。)

    user = User.create(name:&#34; ted&#34;)

    (注意:您也可以使用FactoryGirl的工厂。)

  2. 现在,使用保存在变量&#34; user&#34;中的用户对象,在同一个Rspec测试中执行此操作:

    controller.stub!(:CURRENT_USER).and_return(用户)

  3. 应该有用......

相关问题