I'm trying to test PG database constraints in a rails 4 using RSpec, and I'm not sure how to set it up.

My thought was to do something like this:

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

When I run this, it does in generate an error:

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

However, the test still fails.

Is there a proper syntax to get the test to pass?

有帮助吗?

解决方案

Try

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

For more information, check the more info on rspec-expectations expect-error matchers

Hope this helps!

其他提示

Slight modification to @strivedi183's answer:

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

The justification for being more verbose with the error class is that it protects you from having other possible checks that may raise an error that are not related to specific duplication error you wish to raise.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top