我正在尝试使用 RSpec 来测试我的 Rails 应用程序,该应用程序使用设计用户身份验证 gem。
以下是已捆绑的相关 gem 的列表:
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 generated 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)>'