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

B S*_*ven 29 ruby rspec

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

Foo.where(bar: 1, baz:2).count.should == 1
Run Code Online (Sandbox Code Playgroud)

chr*_*035 39

使用Rspec 2.13.0,我能够做到

Foo.where(bar: 1, baz: 2).should exist
Run Code Online (Sandbox Code Playgroud)

编辑:

Rspec现在有一个期望的语法:

expect(Foo.where(bar: 1, bax: 2)).to exist
Run Code Online (Sandbox Code Playgroud)

  • 当你使用发现者时,`expect(Foo.find_by_bar(1)).to be_present` (11认同)
  • 根据以下指标,“present?”比“exists?”慢 68 倍:https://www.ombulabs.com/blog/benchmark/performance/rails/present-vs-any-vs-exists.html (4认同)

Mug*_*ica 12

对于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
Run Code Online (Sandbox Code Playgroud)


Rim*_*ian 9

使用expect语法:

expect(Foo.where(bar: 1, baz: 2)).not_to be_empty
expect(Foo.where(bar: 1, baz: 2)).to exist
Run Code Online (Sandbox Code Playgroud)


小智 5

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


Sea*_*ill 2

Foo.where(bar: 1, baz: 2).exists?.should be_true
Run Code Online (Sandbox Code Playgroud)