我正在尝试使用RSpec测试rails 4中的PG数据库约束,但我不知道如何设置它。
我的想法是做这样的事情:
before do
@subscriber = Marketing::Subscriber.new(email: "subscriber@example.com")
end
describe "when email address is already taken" do
before do
subscriber_with_same_email = @subscriber.dup
subscriber_with_same_email.email = @subscriber.email.upcase
subscriber_with_same_email.save
end
it "should raise db error when validation is skipped" do
expect(@subscriber.save!(validate: false)).to raise_error
end
end
当我运行这个时,它确实会生成一个错误:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint
然而,测试仍然失败。
是否有正确的语法使测试通过?
尝试
it "should raise db error when validation is skipped" do
expect { @subscriber.save!(validate: false) }.to raise_error
end
有关更多信息,请查看有关rspec预期错误匹配器的更多信息
希望这能有所帮助!
对@奋斗者183的答案进行轻微修改:
it "should raise db error when validation is skipped" do
expect { @subscriber.save!(validate: false) }.to raise_error(ActiveRecord::RecordNotUnique)
end
使用错误类更加详细的理由是,它可以保护您免受其他可能的检查,这些检查可能会引发与您希望引发的特定重复错误无关的错误。