【发布时间】: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=>:open, ...},但它没有构建要关联的项目。当我运行build(:project_item).attributes时,我得到:{... "project_id"=>24,... "status"=>0, ...}。如果我将“状态”更改为'pending'或:pending,它确实给了我相同的错误,用 1 而不是 0。看起来使用 Rails 枚举我将无法以直观的方式构建表单(整数表示标签的值和字符串),所以枚举可能不会让我的生活变得更轻松。
标签: ruby-on-rails rspec enums factory-bot