Is there a better way to check for the existence of a record in RSpec?
Foo.where(bar: 1, baz:2).count.should == 1
使用Rspec 2.13.0,我能够做到
Foo.where(bar: 1, baz: 2).should exist
编辑:
Rspec 现在有一个期望语法:
expect(Foo.where(bar: 1, bax: 2)).to exist
对于 rspec-rails > 3.0
拥有博客模型,
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
使用期望语法:
expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist
利用Foo.exists?(bar: 1, baz: 2).should be_true
Foo.where(bar: 1, baz: 2).exists?.should be_true
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
它对我有用:
expect(Foo.where(bar: 1, baz:2)).not_to be nil