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
How to elegantly check for existence of a record in RSpec
提问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

