我有一个同时使用关联和枚举属性的模型。
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
这失败了,我发现 this issue thread that explains why it doesn't work 。根据评论,我能够确定在具有 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
关于ruby-on-rails - 具有枚举和关联的工厂女孩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606297/