Search code examples
rubyruby-on-rails-4rspec3

rspec model test uniqueness


What would be the proper syntax for testing with rails 4 after the depreciation of validates_uniqueness_of?

in my model...

# prior to Rails 4
validates_uniqueness_of :number

# Rails 4
validates :number, uniqueness: true

in my test file...

# prior to rails 4
it {should validate_uniqueness_of(:number)}

this test fails...

# this fails but with the correct error message expected
it "validates the uniqueness of number" do
  Fabricate(:wo, number: "494949")
  expect{Fabricate.build(:wo, number: "494949")}.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Number has already been taken")
end

What am I doing wrong?


Solution

  • Calling build won't actually run the validations. Try Fabricate(:wo, number: "494949").