shoulda-mathcers での validate_uniquness_of の注意点

class User < ActiveRecord::Base
  validate :name, :unique => true 
end

ActiveRecord の↑のようなモデルの spec として、shoulda-matchers の validate_uniquness_of を使うことがある。

このときこんな風に書くと、場合によって通ったり通らなかったりするので注意が必要。

describe User do
   it { should validate_uniqueness_of(:name) }
end

validate_uniquness_of のドキュメントには以下のようにある。

      # Internally, this uses values from existing records to test validations,
      # so this will always fail if you have not saved at least one record for
      # the model being tested, like so:
      #
      #   describe User do
      #     before(:each) { User.create!(:email => 'address@example.com') }
      #     it { should validate_uniqueness_of(:email) }
      #   end
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb

てなわけで、( factory girl と組み合わせて ) こんな感じでないと安定しなかった。

describe User do
  before { create :user }  
  it { should validate_uniqueness_of(:name) }
end

元のでも他の spec の都合でレコードが残ってたりする場合に通ったりするので、「手元で通るけど jenkins だと通らないよ!」というパターンになるので要注意。