3

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: "[email protected]")
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?

2 Answers 2

6

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Gotta love the syntax errors. Thanks for your help!
Thank you @user2262149. Your method is more elegant than stubbing save and returning either ActiveRecord::RecordNotUnique or PG::UniqueViolation.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.