我正在尝试使用 devise 1.3.4 运行控制器规范。(和工厂女孩)我按照 git wiki 中的说明进行操作。 我能够使用宏中创建的login_user方法以用户身份登录,但login_admin失败并显示以下错误:
...
sign_in Factory.create(:admin)
Could not find a valid mapping for #<User id: 2023, email: "admin1@gmail.com", .... >
厂:
Factory.define :user do |f|
f.sequence(:username) {|n| "user#{n}"}
f.sequence(:email) {|n| "user#{n}@gmail.com"}
f.email_confirmation {|fac| fac.email }
f.password "a12345Den123"
f.password_confirmation "a12345Den123"
# f.admin 0
end
Factory.define :admin, :class => User do |f|
f.sequence(:username) {|n| "admin#{n}"}
f.sequence(:email) {|n| "admin#{n}@gmail.com"}
f.email_confirmation {|fac| fac.email }
f.password "a12345Den123"
f.password_confirmation "a12345Den123"
f.admin 1
end
控制器宏模块:
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user] #it should map to user because admin is not a model of its own. It produces the same result either way.
@admin = Factory.create(:admin)
sign_in @admin
end
end
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = Factory.create(:user)
sign_in @user
end
end
end
路线
devise_for :users
devise_for :admins, :class_name => 'User'
一种解决方案是设置 cache_classes = false,但这并不理想,因为我使用 spork 并且不想在更改模型后重新启动它。
有什么帮助吗?
我的路线中有这样的东西:
devise_for :accounts, :controllers => {:confirmations => "confirmations"} do
put "confirm_account", :to => "confirmations#confirm_account"
get "login" => "devise/sessions#new", :as => :login
delete "logout" => "devise/sessions#destroy", :as => :logout
get "register" => "devise/registrations#new", :as => :register
end
所以在我的规范/支持/controller_macros.rb 中,我需要从:
def login_account
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:account]
@account = Factory.create(:account)
sign_in(@account)
end
end
自
def login_account
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:account]
@account = Factory.create(:account)
sign_in(:account, @account)
end
end
注意sign_in(范围、资源)
我希望这有所帮助。
来自设计自述文件:
Devise 还附带默认路由。 如果需要自定义它们,请 应该可以做到 通过devise_for方法。它 接受几个选项,例如 :class_name、:p ath_prefix 等, 包括更改的可能性 I18n 的路径名
所以我会检查你的路由文件并确保它在那里:
devise_for :admins, :class_name => 'User'
您可能希望在不同位置检查代码中是否存在多个devise_for :admins
声明。在我的情况下,这是导致这种异常的原因,因为它肯定会使Devise感到困惑。