RSpecカスタムマッチャでデータベースのNOT NULL制約をテストする
Railsでモデルを作る時にNOT NULL制約テストを簡単に書きたかったのでカスタムマッチャを作りました。
連載: Rails4のActiveRecord向けRSpecカスタムマッチャ5選
Railsを使っているとDBのフィールドにNOT NULL制約をつけることがよくありますが、テストしようとするとデータを保存してエラーが起きることを確認したりして相当面倒です。
なのでRSpecカスタムマッチャを作りました。
たとえばPersonモデルのnameフィールドのNOT NULL制約をテストする場合は
describe Person do
subject { FactoryGirl.create(:person) }
it { should have_not_null_constraint_on(:title) }
end
と書いてあげれば
$ bundle exec rspec spec/models/person_spec.rb
Person
should have NOT NULL constraint on name
という実行結果になります。
カスタムマッチャはこんな感じです。
RSpec::Matchers.define :have_not_null_constraint_on do |field|
match do |model|
model.send("#{field}=", nil)
begin
model.save!(validate: false)
false
rescue ActiveRecord::StatementInvalid
true
end
end
description { "have NOT NULL constraint on #{field}" }
failure_message { "expected to have NOT NULL constraint on #{field}, but not" }
end
DBのNOT NULL制約はよく使うので重宝しそうです。