我正在尝试编写一个rspec测试,它将检测不同的身份是否具有相同的值(检查提供者和ID的唯一性)
这是我正在进行的测试。我只是扔了一些废话,因为我变得绝望......
context "no duplicate values should exist" do
identity1 = subject { Factory.create(:valid_identity) }
it { should be_valid }
identity2 = identity1
it { should validate_uniqueness_of(:id) }
it { should have(1).error_on(:id) }
it { should validate_uniqueness_of(:provider) }
it { should have(1).error_on(:provider) }
end
为了让你了解我习惯的结构,我已经编写了如下所示的基本测试,如果可能的话,我想坚持使用相同类型的结构
context "when created without a name" do
subject { Brand.create Factory.build(:valid_brand, :name => nil).attributes }
it { should be_invalid }
it { should have(1).error_on(:name) }
specify { subject.errors[:name].should include "can't be blank" }
end
我的身份工厂就是这样:
Factory.define :valid_identity, :class => Identity do |identity|
identity.participant {|participant| participant.association(:valid_participant) }
identity.provider "twitter"
identity.extid '11111'
end
感谢任何帮助!
答案 0 :(得分:0)
您想要的行为是:当我创建一个新对象时,我已经在数据库中拥有一个具有相同提供者/ ID的对象,而不是新对象无效。
在伪代码中,这意味着:
# 1. create a totally valid object and save it in the database
obj1 = create_valid_object_and_save_it
# 2. we need a second object that's totally valid when obj1 exists
obj2 = create_second_valid_object_dont_save_it
# 3. we make the bad condition
obj2.provider = obj1.provider
# 4. now comes the actualy test, obj2 must not be valid!
assert ! obj2.valid?
如果要测试验证,请始终从有效对象开始,然后更改要使其无效的内容。这样你就可以确定你的测试将来不会失败。