B Seven
B Seven

Reputation: 45941

How to elegantly check for existence of a record in RSpec

Is there a better way to check for the existence of a record in RSpec?

Foo.where(bar: 1, baz:2).count.should == 1

Upvotes: 45

Views: 40003

Answers (7)

Nikita Fedyashev
Nikita Fedyashev

Reputation: 19048

RSpec.describe Foo do
  let(:foo_attributes) { { bar: 1, baz: 2 } }
  before { FactoryBot.create(:foo, **foo_attributes) }
  subject { Foo.where foo_attributes }

  it { is_expected.to exist }
end

Upvotes: 0

Helder Itiro Alves
Helder Itiro Alves

Reputation: 21

It worked for me:

expect(Foo.where(bar: 1, baz:2)).not_to be nil

Upvotes: 1

Theo Chirica
Theo Chirica

Reputation: 4516

For rspec-rails > 3.0

Having a Blog model,

describe 'POST #create' do
  it 'creates a post' do
    post :create, blog: { title: 'blog title' }

    # Returns true if the post was successfully added
    expect(Blog.where(title: 'blog title')).to be_present
  end
end

Upvotes: 22

codegoalie
codegoalie

Reputation: 1050

With Rspec 2.13.0, I was able to do

Foo.where(bar: 1, baz: 2).should exist

Edit:

Rspec now has an expect syntax:

expect(Foo.where(bar: 1, bax: 2)).to exist

Upvotes: 51

Rimian
Rimian

Reputation: 38458

Using the expect syntax:

expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist

Upvotes: 9

Richie Min
Richie Min

Reputation: 654

use Foo.exists?(bar: 1, baz: 2).should be_true

Upvotes: 7

Sean Hill
Sean Hill

Reputation: 15056

Foo.where(bar: 1, baz: 2).exists?.should be_true

Upvotes: 2

Related Questions