RSpecでhas_manyのテストヘ(^o^)ノ

Railsでhas_manyなテストするときー

こんなのをテストしたい場合

RSpec.describe Address, :type => :model do
  describe 'Relation' do
    it 'has many customers' do
      expect(address.customers).to match_array customers
    end
  end
end

まずは、FactoryGirlでテストデータを準備

has_manyなので複数のcustomerデータが必要

そんな時はcreate_pair

let(:customers) { create_pair(:customer) }

これで2レコード作成してくれます(便利!

customerの名前とカナをGimeiというgemでランダムに生成します

require 'gimei'

FactoryGirl.define do
  factory :customer do
    gimei = Gimei.new
    name { gimei.kanji }
    kana { gimei.katakana }
  end
end

こんな感じ

でも、これだと同じ名前のデータが作られるので良くない

そんなときはinitialize_with

require 'gimei'

FactoryGirl.define do
  factory :customer do
    initialize_with do
      gimei = Gimei.new
      new(name: gimei.kanji, kana: gimei.katakana)
    end
  end
end

これで、initializeされるたびに名前が作られる(テストは遅くなるかも><

最終的にはこんな感じ

RSpec.describe Address, :type => :model do
  let(:address) { create(:address) }
  let(:customers) { create_pair(:customer, address: address) }

  describe 'Relation' do
    it 'has many customers' do
      expect(address.customers).to match_array customers
    end
  end
end

見やすく、シンプルで良いですねー

他に良い方法があれば教えてくだされーヘ(^o^)ノ

Happy Hacking٩( ‘ω’ )و