【问题标题】:Testing PG Database Constraints with RSpec使用 RSpec 测试 PG 数据库约束
【发布时间】:2014-04-17 03:25:42
【问题描述】:

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

但是,测试仍然失败。

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

【问题讨论】:

    标签: ruby-on-rails postgresql rspec constraints


    【解决方案1】:

    试试

    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

    希望这会有所帮助!

    【讨论】:

    • 喜欢语法错误。感谢您的帮助!
    • 谢谢@user2262149。您的方法比存根 save 并返回 ActiveRecord::RecordNotUnique 或 PG::UniqueViolation 更优雅。
    【解决方案2】:

    对@strivedi183 的回答稍作修改:

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

    对错误类更详细的理由是它可以保护您免受其他可能的检查,这些检查可能会引发与您希望引发的特定重复错误无关的错误。

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      相关资源
      最近更新 更多