2010-12-10 88 views
5

好像我應該能夠在幾個小時的谷歌搜索和測試後找到明顯的答案。工廠女孩的屬性

我希望能夠在caredate工廠內設置caredate.user_id => provider.user_id。

測試錯誤:

​​

我有一個ActiveRecord驗證時,通過瀏覽器進行測試,其工作原理:

class Caredate < ActiveRecord::Base //works fine when testing via browser 
    belongs_to :user 
    belongs_to :provider 

    validates_presence_of :user_id 
    validates_presence_of :provider_id 
    validate :user_must_be_same_as_provider_user 

    def user_must_be_same_as_provider_user 
    errors.add(:user_id, "must be same as provider user") unless self.user_id == self.provider.user_id 
    end 

end 

//factories.rb 
Factory.define :user do |f| 
    f.password "test1234" 
    f.sequence(:email) { |n| "foo#{n}@example.com" } 
end 

Factory.define :caredate do |f| 
    f.association :provider 
    **f.user_id { Provider.find_by_id(provider_id).user_id } //FAILS HERE** 
end 

Factory.define :provider do |f| 
    f.association :user 
end 

我的道歉,如果這以前已經回答;我嘗試了幾種不同的選擇,但無法實現。

更新:這通過驗證,所以我越來越近。我可以用隨機數破解。

Factory.define :caredate do |f| 
    f.association :user, :id => 779 
    f.association :provider, :user_id => 779 
end 

回答

6
Factory.define :caredate do |f| 
    provider = Factory.create(:provider) 
    f.provider provider 
    f.user provider.user 
end 
+0

如果提供程序工廠在cadeate工廠之前在factories.rb中定義,則工作。謝謝! – 2010-12-11 14:55:48

+0

訂單依賴關係是一個很好的觀點,如果兩個工廠是在單獨的文件中定義的,則更爲糟糕。在某些時候,你想知道在這種情況下使用燈具是否更有意義。 – zetetic 2010-12-11 19:37:20

+1

這工作,直到我試圖重建數據庫和加載架構。看起來FactoryGirl正在尋找餐桌。 'rake db:schema:load --trace ... rake中止! 表'claimaway_development.providers'不存在'[Here](http://groups.google.com/group/factory_girl/browse_thread/thread/4852f1a129d72839)是一個討論,但我不能得到這個解決方案的工作。 – 2011-03-20 19:33:56

0

嘗試將USER_ID在after_createafter_build

Factory.define :caredate do |f| 
    f.after_create { |caredate| caredate.user_id = caredate.provider.user_id } 
end 
+0

我假設你的意思是修改現有:caredate廠,否則我得到了多個錯誤:caredate工廠。 不幸的是不工作。我相信驗證在嘗試保存對象時會失敗,所以它永遠不會到達「after_create」階段。 感謝您的建議,但。我繼續嘗試。 – 2010-12-10 20:47:07