我不希望rspec允许我用相同的名称保存类的两个对象,但它确实允许。我缺了什么吗?
我的型号:
class Product < ActiveRecord::Base
validates :title, :description, :image_url, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{.(gif|jpg|png)Z}i,
message: 'must be a URL for GIF, JPG or PNG image'
}
end
我的测试:
describe "when creating products with identical names" do
let(:book1) { FactoryGirl.create(:product, title: 'identical') }
let(:book2) { FactoryGirl.build(:product, title: 'identical') }
it "raises unique validation error" do
expect(book2).not_to be_valid
end
end
这就是我得到的:
1) Product when creating products with identical names raises unique validation error
Failure/Error: expect(book2).not_to be_valid
expected #<Product id: nil, title: "identical", description: "Some crazy wibbles, that are fun", image_url: "freddie_mercury.jpg", price: #<BigDecimal:7f995cdd1358,'0.5699E2',18(27)>, created_at: nil, updated_at: nil> not to be valid
我甚至可以写两次FactoryGirl.create,它只是保存。
然而,如果我切换到rails控制台并尝试创建两个具有两个相同名称的对象,我会收到一个错误。我的测试环境有问题吗?
好吧,book1
不是在测试运行中创建的。。。考虑更改:
describe "when creating products with identical names" do
let(:book1) { FactoryGirl.create(:product, title: 'identical') }
let(:book2) { FactoryGirl.build(:product, title: 'identical') }
it "raises unique validation error" do
expect(book2).not_to be_valid
end
end
至
describe "when creating products with identical names" do
let(:book) { FactoryGirl.build(:product, title: 'identical') }
before do
FactoryGirl.create(:product, title: 'identical')
end
it "raises unique validation error" do
expect(book).not_to be_valid
end
end
这应该会有所帮助!祝你好运