我正在尝试使用 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
有关更多信息,请查看 more info on rspec-expectations expect-error matchers
希望这对您有所帮助!
关于ruby-on-rails - 使用 RSpec 测试 PG 数据库约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124064/