我正在打一场心理障碍。任何人都可以向我解释如何为validate_uniqueness_of编写规范测试?
答案 0 :(得分:19)
或者使用Shoulda:
before do
@user = Factory(:user)
end
subject { @user }
it { should validate_uniqueness_of(:name) }
答案 1 :(得分:15)
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
答案 2 :(得分:3)
使用Shoulda缩短时间:
it "validates uniqueness of name" do
FactoryGirl.create(:tag, name: 'unique name')
should validate_uniqueness_of(:name)
end
答案 3 :(得分:2)
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
答案 4 :(得分:0)
如果您遵循rubocops ImplicitExpect,则可能会使用以下内容:
it { is_expected.to validate(%i[name], uniqueness: { scope: :user_group_id }) }
或
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:user_group_id) }