neezer
neezer

Reputation: 20560

How to spec validates_uniqueness_of in Rspec?

How does one do this? Couldn't find any examples online... (using rspec 2.5.0 & rails 3.0.5)

Upvotes: 5

Views: 6065

Answers (3)

Toady00
Toady00

Reputation: 61

before(:each) do
  @attr = { :bar => "foobar" }
end

it "should reject duplicate bar" do
  Foo.create!(@attr)
  duplicate_bar = Foo.new(@attr)
  duplicate_bar.should_not be_valid
end

Upvotes: 6

johnmcaliley
johnmcaliley

Reputation: 11055

Not sure if this exactly what you are looking for, but you could check the error messages after the save or update

@widget.save
#untested, but this should be close
@widget.errors.full_messages.include?("validation message you are looking for").should be true

But honestly, this is probably not something that you need to test in your unit tests (if that is where you are placing them). You are basically duplicating unit tests that Rails has already done for you. It would be more appropriate to check for the error message in the view in a cucumber integration test.

Upvotes: 0

neezer
neezer

Reputation: 20560

Found it in shoulda-matchers: http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/frames

Upvotes: 10

Related Questions