Search code examples
ruby-on-railsrubyruby-on-rails-3rspecrr

Mocking Validates Uniqueness Callback


How do you mock out the validates :name, uniqueness: true callback for an attribute?

I imagine it would work something like this:

describe "with duplicate name" do
  before { mock(subject.name).unique? { false } }

  it "should be invalid" do
    subject.should have(1).error_on(:name)
  end

Solution

  • Why not using shoulda matchers? With it you can test standard common rails functionality with one-liners like it { should validate_uniqueness_of(:name) }. I find it more readable and eliminates the need for mocking callbacks and preparing test cases