LoginSignup
11
11

More than 5 years have passed since last update.

テストデータジェネレータに Fabrication-gem を使う

Last updated at Posted at 2014-04-16

Mongoid で、embeded_many を使っている時の FactoryGirl を使ったテストデータ作成の方法を調べていたのですが、うまく見つからない・・代わりに Fabrication という物を見つけたので、試してみました。

group :test do
  gem 'fabrication' #追加
end

bundle update した後、/spec/fabricators/{model_name}_fabricator.rb を作る

以下の様な User クラスと UserAccount というクラスがあったとする。

app/models/user.rb
class User
  include Mongoid::Document
  validates_presence_of :name

  field :name,               :type => String
  field :email,              :type => String, :default => ""
  field :password, :type => String, :default => ""

  embeds_many :user_accounts
end
app/models/user_account.rb
class UserAccount
  include Mongoid::Document
  field :provider,            :type => String
  field :uid,                 :type => String
  field :token,               :type => String
  field :auth_response,       :type => String
  FACEBOOK = 'facebook'.freeze
  TWITTER = 'twitter'.freeze

  embeded_in :user, :class_name => "User"
end

これに対して、Userレコードを1つ作るコードはこちら。

spec/fabricators/user_fabricator.rb
Fabricator(:user) do
  id 1
  name 'user'
  email 'hal@test.co.jp'
  password 'password'
  user_accounts(count:1){|attr, i| Fabricate(:user_account) }
end

user_accounts の行で、embeds_many の子どもレコードを作成しています。

spec ファイルから上記データを呼び出す場合はこのようにします。

spec/models/user_account_spec.rb
require 'spec_helper'

describe UserAccount do
  describe '.all' do
    before do
      Fabricate(:user)
      #FactoryGirl.create(:user_account, user: user)
    end
    subject { User.find(1) }
    it { should have(1).user_accounts }
  end

end
11
11
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
11
11