37

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

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

7 回答 7

41

使用Rspec 2.13.0,我能够做到

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

编辑:

Rspec 现在有一个期望语法

expect(Foo.where(bar: 1, bax: 2)).to exist
于 2013-06-17T16:11:14.483 回答
18

对于 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
于 2015-09-16T13:24:14.097 回答
9

使用期望语法:

expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist
于 2013-11-12T04:51:44.167 回答
6

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

于 2012-12-07T03:56:38.867 回答
3
Foo.where(bar: 1, baz: 2).exists?.should be_true
于 2012-12-07T03:45:16.437 回答
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
于 2021-04-21T22:48:21.130 回答
0

它对我有用:

expect(Foo.where(bar: 1, baz:2)).not_to be nil
于 2020-10-13T20:26:13.383 回答