Reputation: 45941
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
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
Reputation: 21
It worked for me:
expect(Foo.where(bar: 1, baz:2)).not_to be nil
Upvotes: 1
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
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
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