LoginSignup
1
1

More than 5 years have passed since last update.

エンドツーエンドテストの fixtures をfactory_girl でセットアップする

Last updated at Posted at 2015-11-16

モバイルアプリのREST クライアントをテストするとき Rails サーバーのモデル群をEnd to End テスト用の内容に登録しておきたいことがあります。

test/fixturesやseeds.rb を使うことも考えたのですが、今ある factories でモデルを作りたいことと今ある spec を直したくないことから、今回は factory_girl を使って fixtures を作成する rake タスクを作ることにしました。

環境

  • rails (4.2.4)
  • factory_girl_rails (4.5.0)

やりたいこと

End to End テストの環境をセットアップするのは db:populate タスクを実行するだけにしたい:

$ ./bin/rake db:populate

factory_girl のインストール

Gemfile の development group に factory_girl_rails を追加します:

# Gemfile
group :development, :test do
  gem 'rspec-rails'
end

Rake ファイルの作成

populate.rake ファイルを次の内容で作成します:

# lib/tasks/db/populate.rake
require 'factory_girl'

namespace :db do
  desc "Populate the database for end-to-end testing"
  task :populate do |t, args|
    puts "Resetting the database"
    Rake::Task['db:reset'].invoke
    puts "Creating the user"
    users = FactoryGirl.create_list(:user, 2)
    users = users.map do |user|
      puts "-- #{user.username}'s token is: #{user.token}"
      user
    end
    puts "Creating a hoge for user"
    users.each do |user|
      FactoryGirl.create(:hoge, user: user)
      puts "-- #{user.username}'s hoge is: #{hoge.inspect}"
    end

    puts "Done!"
  end
end

もちろん spec/factories に users.rb と hoges.rb を作成する必要があります。

# spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    sequence(:token) {|n| "token#{n}" }
# ..
  end
end

Rake タスクの実行

あとは db:populate タスクを実行するだけです:

$ ./bin/rake db:populate
Resetting the database
Creating the user
-- user_1's token is: yyGsiDQ7azGN8-hQGGCPzRV2K4zarkHA
..
Done!

参考資料

1
1
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
1
1