2016-11-27 57 views
1

我有一個具有枚舉屬性的模型。Rails 4:通過FactoryGirl屬性設置枚舉字段

class ApplicationLetter < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :event 

    validates :user, :event, presence: true 

    enum status: {accepted: 1, rejected: 0, pending: 2} 

end 

除了一個工廠,產生這種模式,併爲枚舉

FactoryGirl.define do 
    factory :application_letter do 
    motivation "motivation" 
    user 
    event 
    status :accepted 
    end 
end 

在控制器測試值我想通過出廠

let(:valid_attributes) { FactoryGirl.build(:application_letter).attributes } 

得到有效的屬性並用這些屬性創建一個應用程序。

application = ApplicationLetter.create! valid_attributes 

,但我得到了以下錯誤:

ArgumentError: '1' is not a valid status

爲什麼狀態解釋爲字符串?如果我在工廠中更改狀態,則會得到相同的錯誤,但使用正確的相應編號。

+1

[工廠女孩與枚舉和關聯]可能重複(http://stackoverflow.com/questions/27606297/factory-girl-with-enum-and-association) –

+0

看起來像http://stackoverflow.com/questions/27606297/factory-girl-with-enum-and-association的副本,但那裏也沒有好的答案。如果問題仍然存在,可能希望在[GitHub](https://github.com/thoughtbot/factory_girl)上報告。 –

回答

1
let(:valid_attributes) { FactoryGirl.build(:application_letter).attributes.merge(status: 'accepted') } 
+0

感謝您的快速響應。不幸的是,這並沒有幫助。錯誤仍然完全一樣:/ – Querenker

+0

另外,什麼類型的數據存儲在你的db狀態欄中?這是一個整數字段,是否正確? –

+0

是的,它是一個整數。現在它適用於您更新的答案,如果我在工廠中刪除條目。它看起來有點哈克,但至少它有效。非常感謝:) – Querenker

1

可以更動態地做到這一點:

FactoryGirl.define do 
    factory :application_letter do 
    motivation "motivation" 
    user 
    event 
    status { ApplicationLetter.statuses.values.sample } 
    end 
end 

在這每一次你會得到不同的狀態

,或者如果想使用靜態值,你必須使用整數,因爲enum S按默認使用整數值