我正在设计用于在用户模型上具有单表继承的rails 4应用程序。我们有7个不同类别的用户,每个用户都有自己的ActiveRecord模型,该模型继承自基础User
模型。
我已经完成了我在网络上可以找到的内容,但是我在设置正确的测试时遇到了很多奇怪的问题。我编写了一个自定义sessions_controller来确定哪些类型的用户正在尝试登录并签入正确的资源类,我写了一个小规范来验证它是否正常工作,同时我将其余的功能启动并运行。我似乎无法获得正确的方法来设计使用rspec。我第一次遇到错误:
Failure/Error: post :create, user: { email: 'fake@address.com' }
NoMethodError:
undefined method `authenticate?' for nil:NilClass
这很奇怪,因为我在我的规范帮助文件中包含了devise和warden测试助手(粘贴在下面)。当我在SessionsController规范中直接包含Devise :: TestHelpers时,我得到了一个不同的错误:
1) SessionsController POST create works
Failure/Error: post :create, user: { email: 'fake@address.com' }
ArgumentError:
uncaught throw :warden
# ./app/controllers/sessions_controller.rb:5:in 'create'
# ./spec/controllers/sessions_controller_spec.rb:17:in 'block (3 levels) in <top (required)>'
我已经完成了大量的谷歌搜索,并且只找到了关于将specise和warden测试助手添加到spec文件或在@ request.env上设置“devise.mapping”的建议(两者都是我已经完成的) 。任何和所有的帮助将不胜感激,尤其是指向我未见过的网络教程的指针;)。我看过这些页面:
这是我的sessions_controller.rb:
class SessionsController < Devise::SessionsController
class UnrecognizedUserTypeError < StandardError; end
def create
created = super do
sign_in(type, user_class.try(:find, resource.id))
end
created
end
private
def type
unless User::TYPES.include(type = resource.type.try(:underscore))
raise UnrecognizedUserTypeError
end
type
end
def user_class
type.try(:constantize)
end
end
这是我的sessions_controller_spec.rb:
require 'rails_helper'
describe SessionsController do
# This line should not be needed since it has been included in spec_helper.rb
# but this spec file doesn't seem to work without it (bl 2014-08-11).
include Devise::TestHelpers
before do
setup_controller_for_warden
# Since we're bypassing the router in this test, we need to explicitly
# tell devise which mapping to use.
@request.env["devise.mapping"] = Devise.mappings[:user]
end
describe "POST create" do
it "works" do
post :create
expect(response.code).to eq(200)
end
end
end
以下是我的spec_helper.rb中的相关行(rails_helper要求)
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.include Devise::TestHelpers, type: :controller
config.include Warden::Test::Helpers
config.before(:suite) do
begin
DatabaseCleaner.start
FactoryGirl.lint
Warden.test_mode!
ensure
DatabaseCleaner.clean
end
end
config.after(:suite) do
Warden.test_reset!
end
...
end
以下是config / routes.rb中的相关行:
Rails.application.routes.draw do
devise_for :users, controllers: { sessions: 'sessions' }
devise_for :administrator_users, skip: :sessions
devise_for :manager_users, skip: :sessions
devise_for :adjuster_users, skip: :sessions
devise_for :nurse_case_manager_users, skip: :sessions
devise_for :technical_assistant_users, skip: :sessions
devise_for :provider_users, skip: :sessions
devise_for :super_administrator_users, skip: :sessions
...
end