测试唯一性验证

Testing uniqueness validation

我正在尝试学习 rspec 并遇到了 运行 问题,我正在尝试在我的一个模型上测试唯一性验证,但测试一直失败,即使我我很确定它应该通过。

这是我的测试:

  context "two products with the same title" do
    Given{FactoryGirl.build(:product, title: "Hello test title")}
    Given(:post2){FactoryGirl.build(:product, title: "Hello test title")}
    Then{post2.invalid?}
  end

这是我的验证器:

validates :title, uniqueness: true

然而,当我 运行 测试失败时,我不确定为什么?

任何帮助都会很棒!

您需要在 title 上添加唯一性验证:

validates :title, uniqueness: true

而且你必须先 create product 而不仅仅是 build

context "two products with the same title" do
  Given{FactoryGirl.create(:product, title: "Hello test title")}
  Given(:post2){FactoryGirl.build(:product, title: "Hello test title")}
  Then{post2.invalid?}
end

这将创建一个具有 title = "Hello test title"

的产品

对于具有相同 title 产品的第二个产品将是 invalid

你应该使用像 shoulda-matchers 这样的 gem 来测试这种测试:https://github.com/thoughtbot/shoulda-matchers 它会为你节省很多时间,它会干燥你的测试(因为它们都是一样的)

关于你的测试,我不确定你想要达到什么目的。您不是在那里验证唯一性,只是验证产品的长度。添加您添加到产品模型的唯一性:

validates :title, uniqueness: true

并且在进行测试时,您应该创建(而不是构建)您的第一个产品。基本上,除非您的产品存储在数据库中,否则您的产品将是有效的,因为它(还)不存在任何其他类似的产品。