有没有更好的方法来检查RSpec中是否存在记录?
Foo.where(bar: 1, baz:2).count.should == 1
答案 0 :(得分:33)
使用Rspec 2.13.0,我能够做到
Foo.where(bar: 1, baz: 2).should exist
修改强>
Rspec现在有an expect syntax:
expect(Foo.where(bar: 1, bax: 2)).to exist
答案 1 :(得分:11)
对于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
答案 2 :(得分:8)
使用expect语法:
expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist
答案 3 :(得分:5)
使用Foo.exists?(bar: 1, baz: 2).should be_true
答案 4 :(得分:3)
Foo.where(bar: 1, baz: 2).exists?.should be_true
答案 5 :(得分:0)
对我有用:
expect(Foo.where(bar: 1, baz:2)).not_to be nil
答案 6 :(得分:0)
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