20
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirl使い方メモ

Last updated at Posted at 2013-06-09

model定義

group.rb
class Group < ActiveRecord::Base
  has_many :events
  has_many :members
end
event.rb
class Event < ActiveRecord::Base
  has_many :groups
end

has_manyの定義方法

group_event.rb
FactoryGirl.define do
  factory :seq_group, class: Group do
    sequence(:name) { |n| "group #{n}"}
    sequence(:description) {|n| "description #{n}"}
    sequence(:img_url) {|n| "http://test.com/#{n}.jpg"}
  end

  factory :group_event, class: Group do
    sequence(:name) { |n| "group #{n}"}
    sequence(:description) {|n| "description #{n}"}
    sequence(:img_url) {|n| "http://test.com/#{n}.jpg"}

    events {
      [FactoryGirl.create(:seq_event)]
    }
  end
end

重複を除く為のparent

  • parent: :seq_group」を使ったのですが、もっと便利な書き方があります。
  • ネストして定義しちゃえば、継承出来ます
group_event.rb
FactoryGirl.define do
  factory :seq_group, class: Group do
    sequence(:name) { |n| "group #{n}"}
    sequence(:description) {|n| "description #{n}"}
    sequence(:img_url) {|n| "http://test.com/#{n}.jpg"}

    factory :group_event do
      events {
        [FactoryGirl.create(:seq_event)]
      }
    end
  end
end

配列・リストの作り方

group_event.rb
FactoryGirl.define do
  factory :group_event, class: Group do
    members {
      FactoryGirl.create_list(:seq_user, 10)
    }
  end
end
20
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?