Factory Girl with enum and association

笑着哭i 提交于 2019-12-23 00:52:10

问题


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

回答1:


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



回答2:


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

All you need in your factory is status 'open'



来源:https://stackoverflow.com/questions/27606297/factory-girl-with-enum-and-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!