用设计进行RSpec测试:找不到有效的映射

时间:2011-05-11 15:42:47

标签: ruby-on-rails-3 rspec 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并且不想在更改模型后重新启动它。

任何帮助?

3 个答案:

答案 0 :(得分:6)

我的路线中有这样的东西:

  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

所以在我的spec / support / 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(范围,资源)

我希望这会有所帮助。

答案 1 :(得分:2)

这是来自设计自述文件:

  

Devise还附带默认路线。   如果你需要自定义它们,你   应该可以做到   通过devise_for方法。它   接受几个选项,如   :class_name,:path_prefix等,   包括改变的可能性   I18n的路径名

所以我会检查你的路线文件并确保它在那里:

devise_for :admins, :class_name => 'User'

答案 2 :(得分:0)

您可能希望在不同的地方检查代码中的多个devise_for :admins声明。在我的情况下,这就是造成这种例外的原因,因为它肯定会让Devise感到困惑。