工厂女孩与枚举和协会

时间:2014-12-22 16:12:33

标签: ruby-on-rails rspec enums factory-bot

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

必须在现有工厂调用中添加.merge是一场噩梦。

您在工厂需要的是 status 'open'