FactoryGirlで Hashを定義

FactoryGirlでARではなくhashのモックデータを返してほしいときがある。

そういう場合は以下のようにすればよい。

FactoryGirl.define do
  factory :dog, class: Hash  do
    id 1
    name 'john'
    color 'black'

    initialize_with { attributes }
  end
end

initialize_with は初期化処理を定義できるもので、attributesはFactoryGirlのメソッドだけどattributesの戻り値がHashなのでそのまま使っている感じ。

利用するときはいつものようにbuildが使える。

dog = FactoryGirl.build(:dog, name: 'taro')

参考: http://stackoverflow.com/questions/10032760/how-to-define-an-array-hash-in-factory-girl