Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test the validate_uniqueness_of?

I'm hitting a mental block. Can anyone explain to me how I can write a spec test for validate_uniqueness_of?

like image 534
picardo Avatar asked Jan 13 '11 01:01

picardo


3 Answers

Or use Shoulda:

before do
  @user = Factory(:user)
end

subject { @user }

it { should validate_uniqueness_of(:name) }
like image 119
Tim Avatar answered Oct 23 '22 06:10

Tim


class Foo < ActiveRecord::Base
  validates_uniqueness_of :name
end

# spec
describe Foo do
  it "should have a unique name" do
    Foo.create!(:name=>"Foo")
    foo = Foo.new(:name=>"Foo")
    foo.should_not be_valid
    foo.errors[:name].should include("has already been taken")
  end
end
like image 35
zetetic Avatar answered Oct 23 '22 06:10

zetetic


Make it shorter with Shoulda:

it "validates uniqueness of name" do
  FactoryGirl.create(:tag, name: 'unique name')
  should validate_uniqueness_of(:name)
end
like image 31
Flov Avatar answered Oct 23 '22 07:10

Flov