Search code examples
ruby-on-railstestingrspecscoperspec-rails

How to write a test for validates_uniqueness_of with scope and presence: true RSpec Rails


Trying to write a test to verify uniqueness of :user_id with scope :board_id.

Model:

class Membership < ApplicationRecord
  belongs_to :board
  belongs_to :user
  validates_uniqueness_of :user_id, scope: :board_id, presence: true
end

I try to test it like:

it { should validate_uniqueness_of(:user_id) } 
it expect.to have_many(:membership).through(:board_id)

Thanks for help.


Solution

  • If using shoulda-matchers it can be done in two expectations (even though it's a single model line):

    it { should validate_presence_of(:user_id) }
    it { should validate_uniqueness_of(:user_id).scoped_to(:board_id) }