我的rspec测试中的质量分配错误(Rails.32,activeadmin,rspec)

时间:2013-09-20 21:53:13

标签: ruby-on-rails ruby ruby-on-rails-3 rspec activeadmin

我正在建立一个日常交易应用来学习RoR。

我的问题是关于attr_accessible以及如何测试模型,其中属性受到质量分配的保护。

我的应用中有3个型号:

  • 用户(通过设计)
  • 优惠
  • Admin_users(通过主动admin gem)

基本上,交易属于Admin_users,我只希望管理员用户能够发布交易。

我遇到的问题是,如果我没有错,我需要放置所有属性attr_accessible,以便我可以创建表单并保存交易然后保护属性(特别是admin_user_id)我添加{ {1}} with_role保护他们并且只能由管理员访问(我将其用作灵感:http://ejholmes.github.io/2012/04/22/handling-mass-assignment-with-active-admin.html

我的问题是在放置as: :admin之前正在运行的RSpec测试现在失败了,我得到的错误消息是:

as: :admin

我认为RSpec不会让我成为管理员,所以我有权批量分配这些属性。

我该如何解决这个问题?

以下是我的参考文件:

deal_spec.rb

   ActiveModel::MassAssignmentSecurity::Error:
   Can't mass-assign protected attributes: url_path, country, title, description, twitter_msg, image_url, prelaunch_date, deal_launch_date, deal_end_date, featured, admin_user_id

我的有效管理员设置:on initializers / active_admin.rb

class Deal < ActiveRecord::Base

belongs_to :admin_user, :foreign_key => 'admin_user_id'

attr_accessible :url_path,
              :country,
              :title,
              :description,
              :twitter_msg,
              :image_url,
              :prelaunch_date,
              :deal_launch_date,
              :deal_end_date,
              :featured,
              :admin_user_id,
              :as => :admin_user

validates :title,
          presence: true,
          length: { maximum: 200 }
  • 我的测试文件:

admin_users的工厂:

ActiveAdmin.setup do |config|

config.site_title = "My App"


config.logout_link_path = :destroy_admin_user_session_path


config.batch_actions = true

# got it on http://ejholmes.github.io/2012/04/22/handling-mass-assignment-with-active-admin.html
module ActiveAdmin
 class BaseController
   with_role :admin_user
 end
end

end

实际失败的TEST:这是标题长度测试的一个例子:

FactoryGirl.define do
  factory :admin_user do
  sequence(:email) { |n| "person_#{n}@example.com"}   
  password "admin_pass"
  password_confirmation "admin_pass"
end
end

我觉得我没有告诉我的deal_rspec.rb测试文件:admin_user真的是管理员!我不知道如何做到这一点,即使我正在保护我的交易模型属性与质量分配。有谁知道我怎样才能让这些测试再次通过?

1 个答案:

答案 0 :(得分:1)

这里的问题是:as =&gt; :admin标志不是指active_record模型,它只是您定义的任意符号。使用它意味着你需要在创建调用中传递:: admin这样

Deal.create(params[:deal], as: :admin)

所以你的实际问题可能出在你的工厂,因为它不知道在制作你的对象时传递旗帜。试试这样的事情

factory :deal do
  my_attr "abc"
  initialize_with do
    create(attributes, as: :admin)
  end
end