문제

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