使用 RSpec 测试 PG 数据库约束

GoB*_*616 3 postgresql rspec ruby-on-rails constraints

我正在尝试使用 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
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它确实会产生一个错误:

PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint
Run Code Online (Sandbox Code Playgroud)

但是,测试仍然失败。

是否有正确的语法来让测试通过?

use*_*149 5

尝试

it "should raise db error when validation is skipped" do
  expect { @subscriber.save!(validate: false) }.to raise_error
end
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看有关 rspec-expectations 期望错误匹配器更多信息

希望这可以帮助!