簡単テストライブラリShouldaを使うと、RailsのModelのテストが楽だ。
class RegionTest < ActiveSupport::TestCase
  should_require_attributes :name
  should_require_unique_attributes :roman
end
豊富なマクロのおかげでこんな感じに宣言的にテストが書ける。
でも単体でテストを実行したとき(ruby test/units/region_test.rb)はOKなのにrakeで実行すると(rake test:units)エラーになる。
 33) Failure:
test: Region should require name to be set. (RegionTest)
(略)
/blank/ not found in ["名前を入力してください。"] when set to nil.
<nil> is not true.
 34) Failure:
test: Region should require unique value for roman. (RegionTest)
(略)
/taken/ not found in ["ローマ字はすでに存在します。"] when set to "hokkaidou-touhoku".
<nil> is not true.
うーん・・・。
def should_require_attributes(*attributes)
  message = get_options!(attributes, :message)
  message ||= <strong>/blank/</strong>
  (略)
  end
end
ソースを見てみると、should_require_attributesメソッドはエラーメッセージを/blank/という正規表現で決め打ち比較してるみたい。(validates_presence_ofのデフォルトが”“can‘t be blank”“だから)
そういういい加減なの、嫌いじゃない。
environments読み込むとgettextがエラーメッセージを日本語化するのでエラーになっちゃうのか。
でも、
class RegionTest < ActiveSupport::TestCase
  should_require_attributes :name, 
    :message => "名前を入力してください。" 
  should_require_unique_attributes :roman, 
    :message => "ローマ字はすでに存在します。" 
end
いちいちこんな風にテスト書かなきゃいけないんでは面倒過ぎてアメリカに亡命したくなる。
プラグインより後に何かを読み込むにはどうすりゃいいんだろう?
% tree vendor/plugins/shoulda_ja
vendor/plugins/shoulda_ja
|-- init.rb
`-- lib
    `-- shoulda
        `-- active_record_helpers.rb
良い方法とは思えないけど、プラグインはアルファベット順に読まれるはずなのでshoulda_jaというプラグインを置いて上書きしてみた。
init.rb:
require 'shoulda'
require File.dirname(__FILE__) + '/lib/shoulda/active_record_helpers'
lib/shoulda/active_record_helpers.rb:
module ThoughtBot
  module Shoulda
    module ActiveRecord
      def should_require_attributes(*attributes)
        message = get_options!(attributes, :message)
        message ||= <strong>/入力してください/</strong>
    (略)
      end
      def should_require_unique_attributes(*attributes)
        message, scope = get_options!(attributes, :message, :scoped_to)
        scope = [*scope].compact
        message ||= <strong>/すでに存在します/</strong>
        (略)
      end
    end
  end
end
うほ、動いた。
・・・・・・・・・アドホック!!!
