Closed3

個人アプリ用のminitest

適当適当

今日からRailsガイドを読みながら1つのコントローラのテストを書くことを目指す。
testディレクトリの構造を理解することが必要。

適当適当

test/fixturesについて調べる。
スキャフォで作成されたファイルにここを読めと書いてあった。

◆ メモ
◇ 1モデル1ファイル。
◇ 書き方はこんな感じ。

識別するための名前:
  属性:属性:属性:

◇ レコードの順序を指定したい場合omap YAML typeを使う。

--- !omap
- parent:
    id: 1
    parent_id: nil
    name:- child:
    id: 2
    parent_id: 1
    name:

◇ テスト毎の流れ

  1. test用dbからfixturesのデータ削除
  2. test用dbにfixturesのデータ追加

test/fixtures/*ymlにはERBを書くことができる。
test/fixtures/a.ymlに書いたメソッドは、test/fixtures/b.ymlで使うことはできない。
test/fixtures/a.ymltest/fixtures/b.ymlの両方で使うことができるメソッドは、
次の手順で用意。

  1. test/test_helper.rbにモジュールを書いて、
  2. ActiveRecord::FixtureSet.context_classにincludeする。
module Hoge
  def pom
    'aaa'
  end
end
ActiveRecord::FixtureSet.context_class.include Hoge

◇ 関連付け
belongs_toの表現に外部キーを数字ではなく識別子で指定することができる。

# user.yml
tarou:
  name: tarou
  gender: man

# order.yml ( before )
potate
  price: 150
  user_id: 1 # <= これに注目

# order.yml ( after )
potate
  price: 150
  user_id: tarou # <= これに注目

Polymorphic, has_and_belongs_to_many, has_many :throughの書き方も書いてあった。
気になる人は調べてください。

◇ timestampは自動補完されるらしい。
created_at, created_on, updated_at, updated_onには何も指定しない場合、
現在時刻が追加される。

$LABELラベルを使いまわすことができる。

# user.yml (before)
tarou:
  name: tarou
  gender: man

# user.yml ( after )
tarou:
  name: $LABEL
  gender: man

◇ 使い回し方法が紹介されていた。
一旦は使い回す必要がないから飛ばす。
気になる人は調べてください。
DEFAULTS, _fixture.ignore

適当適当

deviseを使っている場合、
テストの途中でログインする必要がある。
ログインは次の手順

class HogesControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  test 'yahho' do
    # sign_in fixtureのファイル名(フィクスチャのラベル名)
    sign_in users(:tarou)
  end
end
このスクラップは2ヶ月前にクローズされました