开发者

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?


Or use Shoulda:

before do
  @user = Factory(:user)
end

subject { @user }

it { should validate_uniqueness_of(:name) }


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


Make it shorter with Shoulda:

it "validates uniqueness of name" do
  FactoryGirl.create(:tag, name: 'unique name')
  should validate_uniqueness_of(:name)
end


class User < ActiveRecord::Base
  validates_uniqueness_of :name
end


it "should validate uniqueness of name" do
  user1 = FactoryGirl.create(:user)
  user1.save
  user2 = FactoryGirl.build(:user)
  expect { user2.save! }.to raise_error(
    ActiveRecord::RecordInvalid
  )      
end


In case you follow rubocops ImplicitExpect you might what to use something like this:

it { is_expected.to validate(%i[name], uniqueness: { scope: :user_group_id }) }

or

it { is_expected.to validate_uniqueness_of(:name).scoped_to(:user_group_id) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜