IT story

Has_many 연관을 사용하여 FactoryGirl에서 공장을 설정하는 방법

hot-time 2020. 9. 15. 19:22
반응형

Has_many 연관을 사용하여 FactoryGirl에서 공장을 설정하는 방법


내가 잘못된 방식으로 설정하는 경우 누군가 말해 줄 수 있습니까?

has_many.through 연관이있는 다음 모델이 있습니다.

class Listing < ActiveRecord::Base
  attr_accessible ... 

  has_many :listing_features
  has_many :features, :through => :listing_features

  validates_presence_of ...
  ...  
end


class Feature < ActiveRecord::Base
  attr_accessible ...

  validates_presence_of ...
  validates_uniqueness_of ...

  has_many :listing_features
  has_many :listings, :through => :listing_features
end


class ListingFeature < ActiveRecord::Base
  attr_accessible :feature_id, :listing_id

  belongs_to :feature  
  belongs_to :listing
end

Rails 3.1.rc4, FactoryGirl 2.0.2, factory_girl_rails 1.1.0 및 rspec을 사용하고 있습니다. 다음은 :listing공장에 대한 기본적인 rspec rspec 온 전성 검사입니다 .

it "creates a valid listing from factory" do
  Factory(:listing).should be_valid
end

여기는 Factory (: listing)

FactoryGirl.define do
  factory :listing do
    headline    'headline'
    home_desc   'this is the home description'
    association :user, :factory => :user
    association :layout, :factory => :layout
    association :features, :factory => :feature
  end
end

:listing_feature:feature공장 유사하게 설정합니다.
는 IF association :features라인이 주석 다음 내 모든 테스트를 통과.

association :features, :factory => :feature

오류 메시지는 배열을 반환 undefined method 'each' for #<Feature>하기 때문에 나에게 의미가 있다고 생각했습니다 listing.features. 그래서 나는 그것을

association :features, [:factory => :feature]

and the error I get now is ArgumentError: Not registered: features Is it just not sensible to be generating factory objects this way, or what am I missing? Thanks very much for any and all input!


Creating these kinds of associations requires using FactoryGirl's callbacks.

A perfect set of examples can be found here.

https://thoughtbot.com/blog/aint-no-calla-back-girl

To bring it home to your example.

Factory.define :listing_with_features, :parent => :listing do |listing|
  listing.after_create { |l| Factory(:feature, :listing => l)  }
  #or some for loop to generate X features
end

Alternatively, you can use a block and skip the association keyword. This makes it possible to build objects without saving to the database (otherwise, a has_many association will save your records to the db, even if you use the build function instead of create).

FactoryGirl.define do
  factory :listing_with_features, :parent => :listing do |listing|
    features { build_list :feature, 3 }
  end
end

You could use trait:

FactoryGirl.define do
  factory :listing do
    ...

    trait :with_features do
      features { build_list :feature, 3 }
    end
  end
end

With callback, if you need DB creation:

...

trait :with_features do
  after(:create) do |listing|
    create_list(:feature, 3, listing: listing)
  end
end

Use in your specs like this:

let(:listing) { create(:listing, :with_features) }

This will remove duplication in your factories and be more reusable.

https://robots.thoughtbot.com/remove-duplication-with-factorygirls-traits


I tried a few different approaches and this is the one that worked most reliably for me (adapted to your case)

FactoryGirl.define do
  factory :user do
    # some details
  end

  factory :layout do
    # some details
  end

  factory :feature do
    # some details
  end

  factory :listing do
    headline    'headline'
    home_desc   'this is the home description'
    association :user, factory: :user
    association :layout, factory: :layout
    after(:create) do |liztng|
      FactoryGirl.create_list(:feature, 1, listing: liztng)
    end
  end
end

Here is how I set mine up:

# Model 1 PreferenceSet
class PreferenceSet < ActiveRecord::Base
  belongs_to :user
  has_many :preferences, dependent: :destroy
end

#Model 2 Preference

class Preference < ActiveRecord::Base    
  belongs_to :preference_set
end



# factories/preference_set.rb

FactoryGirl.define do
  factory :preference_set do
    user factory: :user
    filter_name "market, filter_structure"

    factory :preference_set_with_preferences do
      after(:create) do |preference|
        create(:preference, preference_set: preference)
        create(:filter_structure_preference, preference_set: preference)
      end
    end
  end

end

# factories/preference.rb

FactoryGirl.define do
  factory :preference do |p|
    filter_name "market"
    filter_value "12"
  end

  factory :filter_structure_preference, parent: :preference do
    filter_name "structure"
    filter_value "7"
  end
end

And then in your tests you can do:

@preference_set = FactoryGirl.create(:preference_set_with_preferences)

Hope that helps.

참고URL : https://stackoverflow.com/questions/6963298/how-to-set-up-factory-in-factorygirl-with-has-many-association

반응형

'IT story' 카테고리의 다른 글

LaTeX 테이블 포지셔닝  (0) 2020.09.15
HTTP 헤더 설정 NSURLRequest  (0) 2020.09.15
NSDictionary의 모든 키를 NSArray로 가져옵니다.  (0) 2020.09.15
레일 번들 청소  (0) 2020.09.15
jquery, id 내의 클래스 선택자  (0) 2020.09.15