使用RSpec测试PG数据库约束

时间:2014-04-17 03:25:42

标签: ruby-on-rails postgresql rspec 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

当我运行它时,它会产生错误:

PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint

然而,测试仍然失败。

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

1 个答案:

答案 0 :(得分:4)

尝试

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

希望这有帮助!