2015-08-15 68 views
1

我們定義了以下模型爲什麼我的工廠不認可我的泳池協會?

class UserPool < ActiveRecord::Base 
    belongs_to :pool 
    belongs_to :user 
    validates :pool, presence: true 
    validates :user, presence: true 

    def self.created(date) 
     where("DATE(created_at) = ?", date) 
    end 
    end 

及以下Factroy

FactoryGirl.define do 
    factory :user_pool do 
     pool 
     user 

     factory :paid_user_pool do 
     money_on_pool 10 
     end 
    end 
    end 

當我運行下面的測試中,我recive錯誤

describe "obtain users_pools created at specifict time" do 
    before do 
     users = create_list :user, 3, active: false 
     user4 = create :user 

     @pool = create :pool 
     users.each do |user| 
     create :user_pool, user: user, pool: @pool, created_at: 1.days.ago 
     end 
     create :user_pool, user: user4, pool: @pool 
    end 

    it "should return just users_pools created at specifict time" do 
     users_pools = @pool.user_pools.created(1.days.ago) 
     users_pools.count.should eq 3 
    end 
    end 

錯誤:

ActiveRecord::RecordInvalid: 
    The validation failed: Pool can’t be blank 

爲什麼我的工廠不認可我的泳池協會?

+0

請看我的答案,並讓我知道如果這可以解決您的問題。如果沒有,請顯示完整的錯誤日誌。 –

+0

爲了澄清,你確實有一個「Pool」類,對吧? – onebree

+0

你還有問題嗎?你需要提供的其他細節? – onebree

回答

0

創建工廠時,可以列出具有預定義值的屬性。否則,您可以從工廠中省略它們,並在測試中明確聲明它(在創建過程中)。

# Example for :user 
factory :user do 
    sequence(:name) { |n| "Test User #{n}" } 
end 

現在,當你調用create(:user),默認名稱將包括一個數字,以1爲創建的每個用戶增加。有關更多信息,請參閱#sequence"Sequences"

現在到你的具體例子。您可以通過以下兩種方式之一創建user_pool工廠。

# No default attributes, requires explicit assignment 
factory :user_pool do 
end 
create(:user_pool, user: user, pool: @pool) 

# Default attributes can be overridden during test 
# Requires you to create :user and :pool factories 
factory :user_pool do 
    after(:build) do |user_pool| 
    user_pool.user = create(:user) 
    user_pool.pool = create(:pool) 
    end 
end 

當你的build是一個ActiveRecord對象時,它不會被提交給數據庫。您可以忽略必要的屬性。構建對象後,會創建兩個(user,pool),並將其分配給正確的user_pool屬性。請參閱文檔"Callbacks"以獲取更多信息。

如果您想在測試中創建@pool,仍然可以執行以下操作。它將覆蓋默認的pooluser屬性。

user_pool = create(:user_pool, user: user, pool: @pool) 
0

因爲您的關聯對象沒有正確創建。所以,驗證失敗。

不要保存相關的對象,在工廠指定strategy: :build

factory :user_pool do 
    association :pool, factory: :pool, strategy: :build 
    association : user, factory: :user, strategy: :build 
end 

然後,使用build代替create

pool = build(:pool) 
. . . 
. . . 

this discussion會給你有關問題的更多見解。