Rails 4:通过FactoryGirl属性设置枚举字段

Rails 4: Set enum field through FactoryGirl attributes

我有一个以枚举作为属性的模型。

class ApplicationLetter < ActiveRecord::Base
  belongs_to :user
  belongs_to :event

  validates :user, :event, presence: true

  enum status: {accepted: 1, rejected: 0, pending: 2}

end

以及生成此模型并为枚举设置值的工厂

FactoryGirl.define do
  factory :application_letter do
    motivation "motivation"
    user
    event
    status :accepted
  end
end

在控制器测试中我想通过工厂获取有效属性

let(:valid_attributes) { FactoryGirl.build(:application_letter).attributes }

并创建具有这些属性的应用程序。

application = ApplicationLetter.create! valid_attributes

但我收到以下错误:

ArgumentError: '1' is not a valid status

为什么状态被解释为字符串?如果我在工厂中更改状态,我会得到相同的错误,但对应的数字是正确的。

let(:valid_attributes) { FactoryGirl.build(:application_letter).attributes.merge(status: 'accepted') }

你可以更动态地做到这一点:

FactoryGirl.define do
  factory :application_letter do
    motivation "motivation"
    user
    event
    status { ApplicationLetter.statuses.values.sample }
  end
end

在此每次您将获得不同的状态

或者如果想使用静态值你必须使用整数,因为 enums 默认使用整数值

你的工厂只需要status 'accepted'