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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13756569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:34:58  来源:igfitidea点击:

How to elegantly check for existence of a record in RSpec

rubyrspec

提问by B Seven

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

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

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

回答by chrismar035

With Rspec 2.13.0, I was able to do

使用Rspec 2.13.0,我能够做到

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


Edit:

编辑:

Rspec now has an expect syntax:

Rspec 现在有一个期望语法

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

回答by Mugur 'Bud' Chirica

For rspec-rails > 3.0

对于 rspec-rails > 3.0

Having a Blog model,

有一个博客模型,

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

回答by Rimian

Using the expect syntax:

使用期望语法:

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

回答by Richie Min

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

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

回答by Sean Hill

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