rspec无法使用设计用户身份验证

时间:2014-12-05 02:41:13

标签: ruby-on-rails rspec devise

我正在尝试使用RSpec来测试使用设计用户身份验证gem的rails应用程序。

以下是已捆绑的相关宝石列表:

devise (3.4.1)
rails (4.1.7, 4.1.6)
rspec (3.1.0)
rspec-core (3.1.7)
rspec-expectations (3.1.2)
rspec-mocks (3.1.3)
rspec-rails (3.1.0)
rspec-support (3.1.2)

根据devise和rspec的文档,我有一个spec / controller / feed_controller_spec.rb,如下所示:

require 'rails_helper'

RSpec.describe FeedController, :type => :controller do

  before(:each) do
    devise_setup
  end

  it "blocks unauthenticated access" do
    get :index
    response.should redirect_to(new_user_session_path)
  end

  it "allows authenticated access" do
    user = User.create!(:foo => 'bar', ...)
    sign_in user
    get :index
    expect(response).to be_success
  end
end

在我的spec / support / controller_macros.rb文件中:

module ControllerMacros
  def devise_setup
      allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
      allow(controller).to receive(:current_user).and_return(nil)
  end

  def sign_in(user)
    if user.nil?
      allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
      allow(controller).to receive(:current_user).and_return(nil)
    else
      allow(request.env['warden']).to receive(:authenticate!).and_return(user)
      allow(controller).to receive(:current_user).and_return(user)
    end
  end
end

最后但并非最不重要的是我的spec / spec_helper.rb文件有以下添加的行(在使用rails生成的文件的顶部生成rspec:init命令):

require 'devise'

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end

当我在命令行上运行bundle exec rspec时,我收到以下错误:

/.../spec/spec_helper.rb:6:in `block in <top (required)>': uninitialized constant ControllerMacros (NameError)
    from /usr/local/lib/ruby/gems/2.1.0/gems/rspec-core-3.1.7/lib/rspec/core.rb:81:in `configure'
    from /home/vagrant/code/pulse/spec/spec_helper.rb:4:in `<top (required)>'

当我从spec_helper.rb文件中注释掉ControlMacros行时,它提供以下内容:

1) FeedController blocks unauthenticated access
   Failure/Error: devise_setup
   NameError:
     undefined local variable or method `devise_setup' for #<RSpec::ExampleGroups::FeedController:0xba5d20f4>
   # ./spec/controllers/feed_controller_spec.rb:9:in `block (2 levels) in <top (required)>'

2) FeedController allows authenticated access
   Failure/Error: devise_setup
   NameError:
     undefined local variable or method `devise_setup' for #<RSpec::ExampleGroups::FeedController:0xba5c76a4>
   # ./spec/controllers/feed_controller_spec.rb:9:in `block (2 levels) in <top (required)>'

2 个答案:

答案 0 :(得分:10)

好像你需要require 'support/controller_macros'spec/support子目录中的文件是自动加载的,但不是必需的。

答案 1 :(得分:5)

取消注释/在rails helper中添加此行:

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }