2013-07-15 81 views
3

我想用FactoryGirl 4.2.0正確建立一個多對多的工廠集。我一直使用混合在一起的舊版FactoryGirl版本語法過時的文檔/示例,它只是不適合我。factory_girl(4.2.0)多對多關係

我如何設置此方案給出以下兩種資源,他們的鏈接表:

class User < ActiveRecord::Base 
    has_many :user_registrations 
    has_many :registrations, through: :user_registrations 
end 

class UserRegistration < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :registration 
end 

class Registration < ActiveRecord::Base 
    has_many :user_registrations 
    has_many :users, through: :user_registrations 
end 

這是我到目前爲止,按照文檔found here。這距離我到達任何真正的進步很近。

FactoryGirl.define do 

    factory :registration do 
    user 
    end 

    factory :user, class: User do 
    sequence(:email) { |n| "foo#{n}@example.com" } 
    password "password" 

    factory :user_with_registrations do 

     ignore do 
     registrations_count 1 
     end 

     after(:create) do |user, evaluator| 
     registrations FactoryGirl.create_list(:registration, evaluator.registrations_count, user: user) 
     end 
    end 
    end 
end 

以下列方式失敗,我意識到這是因爲這個設置被認爲是一對多的關係。

1) User Login Success 
    Failure/Error: user = FactoryGirl.create(:user_with_registrations) 
    NoMethodError: 
     undefined method `user=' for #<Registration:0x007fc48e2ca768> 
    # ./spec/factories.rb:18:in `block (4 levels) in <top (required)>' 

什麼是使用最新FactoryGirl語法爲多對多場景定義工廠集的正確方法? (4.2.0)

謝謝!

回答

6

對於我來說,就像lookes你必須通過UserRegistrations使has_many協會的RegistrationsUsers。這將看起來像

factory :user_registration do 
     association :user 
     association :registration 
    end 

    factory :user do 
     ..setup for email and password 

     factory :user_with_registrations do 

      ignore do 
      registrations_count 1 
      end 

      after(:create) do |user, evaluator| 
      FactoryGirl.create_list(:user_registration, evaluator.registrations_count, user: user) 
      end 
     end 
    end 

    factory :registration do 
     ..setup for registration 

     factory :registration_with_user do 

      ignore do 
      users_count 1 
      end 

      after(:create) do |registration, evaluator| 
      FactoryGirl.create_list(:user_registration, evaluator.users_count, registration: registration) 
      end 
     end 
    end 
+0

謝謝你的工作! 僅供參考:我決定與我的工廠測試需求的加​​工商。看起來更清潔,我已經把所有的東西都轉換過來了。我可能會在未來的應用程序中使用factory_girl來測試差異。 – t0rpedo

+0

絕對救生員,非常感謝 – Omni

0

我想我以前遇到過這個問題(不太明顯,你會同意的),你在工廠定義中使用了一個常量名。

嘗試使用一個字符串,而不是像這樣:

factory :user, class: 'User' do 
    ... 
+0

沒有。無論哪種方式,它仍然響應相同。 – t0rpedo