工厂女孩与枚举和协会

我有一个使用关联和枚举属性的模型。

class ProjectItem < ActiveRecord::Base belongs_to :project enum status: {open: 0, pending: 1, completed: 2} 

当我在带有关联的模型的创建操作上运行测试时,我使用build(:model_name).attributes如下所示:

 it "creates a new ProjectItem" do expect { post :create, document_project_item: build(:project_item).attributes }.to change(ProjectItem, :count).by(1) end 

这是失败的,我发现这个问题线程解释了为什么它不起作用 。 根据评论,我能够确定在具有enum属性但没有关联的表上,按预期方式使用attributes_for(:model_name)

问题主题似乎没有建议解决方法,但我承认我不明白FactoryGirl方法在幕后所做的100%。 这是工厂:

 factory :project_item do project name { Faker::Company.bs } description { Faker::Lorem.paragraph } status :open due { Faker::Date.between(2.days.ago, 10.days.from_now) } sequence(:position) {|n| n } completed_at { Faker::Date.between(1.year.ago, Date.today) } end 

我也尝试在status放置一个整数,但是我得到了同样的错误:

  Failure/Error: post :create, project_item: build(:project_item).attributes ArgumentError: '0' is not a valid status 

我对其他解决方案持开放态度,但这是我提出的解决方法。

 let(:project_attributes) { build(:project_item).attributes.merge(status: 'pending') } it "creates a new ProjectItem" do expect { post :create, project_id: project.id, project_item: project_attributes }.to change(ProjectItem, :count).by(1) end 

.merge在预先存在的工厂电话中添加.merge是一场噩梦。

您工厂所需要的只是status 'open'