1
我有一個同時使用關聯和枚舉屬性的模型。枚舉和關聯的工廠女孩
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方法在幕後做了什麼。這裏的工廠:
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的響應中的狀態值?此外,嘗試使用'pending'而不是'open',看看你是否得到'1'而不是'0'的錯誤。 – Humza
當我從控制檯運行'attributes_for'時,我得到:'{...:status =>:open,...}',但它不構建要關聯的項目。當我運行'build(:project_item).attributes'時,我得到:'{...「project_id」=> 24,...「status」=> 0,...}'。如果我把'status'改爲''pending''或者':pending',它確實會給我帶來與1相同的錯誤,而不是0.它看起來像使用Rails枚舉我不會以直觀的方式構建表單整數值和字符串的標籤),所以它可能是枚舉不會讓我的生活在這一點上更容易。 – Shaun