【问题标题】:Factory Girl with enum and association具有枚举和关联的工厂女孩
【发布时间】:2014-12-22 16:12:33
【问题描述】:

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

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

【问题讨论】:

  • 你检查过 attributes_for 或 build(something).attributes 响应中的 status 值吗?另外,尝试使用pending 而不是open,看看你是否在使用1 而不是0 时遇到同样的错误。
  • 当我从控制台运行attributes_for 时,我得到:{... :status=&gt;:open, ...},但它没有构建要关联的项目。当我运行build(:project_item).attributes 时,我得到:{... "project_id"=&gt;24,... "status"=&gt;0, ...}。如果我将“状态”更改为'pending':pending,它确实给了我相同的错误,用 1 而不是 0。看起来使用 Rails 枚举我将无法以直观的方式构建表单(整数表示标签的值和字符串),所以枚举可能不会让我的生活变得更轻松。

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


【解决方案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

【讨论】:

    【解决方案2】:

    必须在预先存在的工厂调用中添加.merge 是一场噩梦。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多