如何优雅地在RSpec中检查记录是否存在

43

在RSpec中,有没有更好的方法来检查记录是否存在?

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

1
你可以尝试一下 Foo.where(bar: 1, baz:2).should_not be_empty 吗? - Dogbert
7个回答

48

使用 Rspec 2.13.0,我能够做到

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

编辑:

Rspec现在有一个expect语法

expect(Foo.where(bar: 1, bax: 2)).to exist

25
当您使用查找器时,expect(Foo.find_by_bar(1)).to be_present - Andrei
4
根据此基准测试,“present?”比“exists?”慢了68倍:https://www.ombulabs.com/blog/benchmark/performance/rails/present-vs-any-vs-exists.html - sekrett

21

对于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

9

使用expect语法:

expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist

7

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


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

1

它对我有效:

expect(Foo.where(bar: 1, baz:2)).not_to be nil

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

请解释您的代码是做什么的以及它如何实现。 - M-Chen-3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接