LoginSignup
3
5

More than 5 years have passed since last update.

RSpecカスタムマッチャでデータベースのUNIQUE制約を簡単にテストする

Posted at

Railsを使っているとDBのフィールドにUNIQUE制約をつけることがよくありますが、テストしようとするとデータを保存してエラーが起きることを確認したりして相当面倒です。
なのでカスタムマッチャを作りました。

たとえばPersonモデルのnameフィールドのUNIQUE制約をテストする場合は

describe Person do
  subject { FactoryGirl.create(:name) }
  it { should have_not_null_constraint_on(:title) }
end

と書いてあげれば

$ bundle exec rspec spec/models/person_spec.rb
Person
  should have UNIQUE constraint on name

とテスト実行できます。

カスタムマッチャのソースコードは下記の記事に書きました。

ちなみに他にこんな記事も書いています。

3
5
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
3
5