LoginSignup
92
80

More than 5 years have passed since last update.

Railsのテストで初期データ投入をしてくれるFixtureのつかいかた

Last updated at Posted at 2014-11-15

Ruby on Rails Guides - A Guide to Testing Rails ApplicationsのFixturesの項の覚書

コード例も基本Rails Guidesのものです

基本

FixtureはYAMLで記述する
DBへのFixturesのデータ投入はテスト実行前に行われる

以下、記述例

users.yml
david:
  name: David Heinemeier Hansson
  birthday: 1979-10-15
  profession: Systems development

steve:
  name: Steve Ross Kellock
  birthday: 1974-09-27
  profession: guy with keyboard

モデルの関連(Model Associations)

例えばhas_many :articles, belongs_to :categoryの場合、
以下のように書くことでモデルの関連を定義することが可能

fixtures/categories.yml
about:
  name: About
fixtures/articles.yml
one:
  category: about # Model名: fixture定義名

ERB

RailsのFixturesではERBを埋め込むことができる。
ERBはRailsにFixtureがloadされた時に実行される。

例として、以下のように書くと1000件のユーザーが作成される。

<% 1000.times do |n| %>
user_<%= n %>:
  username: <%= "user#{n}" %>
  email: <%= "user#{n}@example.com" %>
<% end %>

テスト実行時の挙動

  • Fixtureに関係するDBのtableのデータを取り除く
  • Fixtureを読み込む
  • Fixture定義データを変数に格納する(以下を参照)

Fixture定義データをActiveRecordオブジェクトとして利用

Fixtureは以下のように書くことでテスト中にActiveRecordのオブジェクトとして用いることができる。

# 以下のように記述する
# <fixtureファイル名>(:<定義名>)

# this will return the User object for the fixture named david
users(:david)

# this will return the property for david called id
users(:david).id

# one can also access methods available on the User class
email(david.girlfriend.email, david.location_tonight)

参考

Ruby on Rails Guides
有頂天Ruby - 私がMinitestとRailsのFixturesにハマった7つの理由

92
80
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
92
80