简体   繁体   中英

Factory Girl with enum and association

I have a model that uses both an association and an enum attribute.

class ProjectItem < ActiveRecord::Base
  belongs_to :project

  enum status: {open: 0, pending: 1, completed: 2}

When I'm running a test on the create action of a model with an association, I use build(:model_name).attributes like this:

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

This was failing, and I found this issue thread that explains why it doesn't work . Based on the comment, I was able to determine that on tables with an enum attribute but no association, things work with attributes_for(:model_name) as expected.

The issue thread doesn't seem to suggest a work around, though I'll admit I don't understand what 100% of what the FactoryGirl methods are doing behind the scenes. Here's the factory:

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

I tried putting an integer in status as well, but I get the same error:

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

I'm open to other solutions, but this is what I came up with as a workaround.

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

Having to add a .merge across pre-existing factory calls is a nightmare.

All you need in your factory is status 'open'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM