haracaneのブログ
Rails4のActiveRecord向けRSpecカスタムマッチャ5選(第1回)
RSpec

RSpecカスタムマッチャでデータベースのNOT NULL制約をテストする

Railsでモデルを作る時にNOT NULL制約テストを簡単に書きたかったのでカスタムマッチャを作りました。 (2014/09/08)

RSpecカスタムマッチャでデータベースのNOT NULL制約をテストする

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制約はよく使うので重宝しそうです。

関連記事

  • このエントリーをはてなブックマークに追加
  • follow us in feedly