Fabricator(:person) do # テストデータ生成ライブラリを使う name { Faker::Name.name } # ランダムな値を使う job { %w( Singer Desinger Manager).sample } end ブロックも使える
Fabricator(:person) do name { %w(alice bob carol).sample } # 名前からメールアドレスを決める email { |person| "#{ person.name }@example.com" } end 属性は上から順に決まっていく
Fabricator(:person) do ssn { sequence(:ssn, 111111111) } email { sequence(:email) { |i| "user#{i}@example.com" } } end ユニーク制約にはSequence
class Person belongs_to :vehicle # 乗り物 validates :vehicle_id, presence: true # … は必須 end # Vehicle は↓これでいいとして、 class Vehicle validates :name, presence: true end Fabricator(:vehicle) do name 'name1' end 例:Personは必ずVehicleを持つ
# こう書けるが、 Fabricator(:person) do vehicle { Fabricate( :vehicle ) } end # これでも同じ意味になる Fabricator(:person) do vehicle end ただ属性名だけを書く
例:属性名とモデル名が違う場合 class Person belongs_to :ride, class_name: 'Vehicle' validates :vehicle_id, presence: true end # person.vehicle ではなく person.ride # で Vehicle オブジェクトにアクセス
:fabricatorオプションを渡す # こう書けるが Fabricator(:person) do ride { Fabricate( :vehicle ) } end # これでも同じ意味になる Fabricator(:person) do ride( fabricator: :vehicle ) end
継承 Fabricator(:person) do name 'name1' age 20 end # :person をベースに :child を定義する Fabricator(:child, from: :person ) do age 10 end child = Fabricate(:child) child.name # => 'name1' child.age # => 10
対コンストラクタ # x と y が無いと new できない class Location def initialize(x, y) @x, @y = x, y end end Fabricator(:location) do on_init { init_with (30.284167, -81.396111) } end
describe User do it 'full_name は苗字+名前になる ' do user = Fabricate(:user) user.full_name.should == 'Yamada Taro' end end テストの可読性
テスト対象の値は明示する。 it 'full_name は苗字+名前になる ' do user = Fabricate(:user, first_name: 'Taro', last_name: 'Yamada' ) user.full_name.should == 'Yamada Taro' end