用RSpec测试PG数据库约束

3

我正在尝试使用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

然而,测试仍然失败。
有没有正确的语法可以使测试通过?
2个回答

6

一定要喜欢语法错误。谢谢你的帮助! - GoBlue1616
谢谢@user2262149。您的方法比存根“save”并返回ActiveRecord :: RecordNotUnique或PG :: UniqueViolation更加优雅。 - scarver2

1

对 @strivedi183 的回答进行轻微修改:

it "should raise db error when validation is skipped" do
   expect { @subscriber.save!(validate: false) }.to raise_error(ActiveRecord::RecordNotUnique)
end

错误类更加详细的理由在于它可以保护你免受其他可能引发错误的检查的影响,这些检查与你希望引发的特定重复错误无关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接