在RSpec中,有没有更好的方法来检查记录是否存在?
Foo.where(bar: 1, baz:2).count.should == 1
使用 Rspec 2.13.0,我能够做到
Foo.where(bar: 1, baz: 2).should exist
编辑:
Rspec现在有一个expect语法:
expect(Foo.where(bar: 1, bax: 2)).to exist
expect(Foo.find_by_bar(1)).to be_present
。 - Andrei对于rspec-rails > 3.0
如果有一个Blog模型,
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语法:
expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist
use Foo.exists?(bar: 1, baz: 2).should be_true
Foo.where(bar: 1, baz: 2).exists?.should be_true
它对我有效:
expect(Foo.where(bar: 1, baz:2)).not_to be nil
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
Foo.where(bar: 1, baz:2).should_not be_empty
吗? - Dogbert