LoginSignup
4
6

More than 5 years have passed since last update.

Railsでfixtureを分割してテストする

Posted at

1つのモデルに対して1つのfixtureだとテストがとてもしんどいことがあるので、1つのモデルに対して複数のfixtureを用意してテストする方法。結構強引かも・・・

test/fixtureいかにymlたくさん作ってもいいかもしれないけどグルーピングさせたほうがわかりやすいので、test/fixtures以下にサブディレクトリをきって、そこにymlを配置する。例えばこんな感じ。

test/fixtures/admin/admin_users.yml

users.ymlが他の場所にもあるとエラーになるので、別の名前(admin_users)をつける。
次にtest_helper.rbの以下をコメントアウト。

test_helper.rb
fixtures :all

これコメントアウトしないと、サブディレクトリも勝手に読みにいって、いろいろエラーになる。

で、テストコードを以下のようにする。

user_controller_test.rb
require 'test_helper'
require "active_record/fixtures"

class UserControllerTest < ActionController::TestCase
  def setup
    directory = Rails.root.join("test", "fixtures", "admin")  #①
    ActiveRecord::FixtureSet.create_fixtures(directory, "adnim_users", :admin_users => User) #②
  end
end

①新規にきったサブディレクトリへのパス
②指定したサブディレクトリからymlを読み込んでUserモデルを作成する

もっといいやり方あるんだろうな・・・

4
6
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
4
6