如何解决如何为类方法编写测试Rspec?
我是RSpec的新手,所以这确实让我头疼。我在Post模型中按关键字或按类别进行搜索:
def self.search(search,category_id)
if search.strip.empty?
[]
elsif category_id.empty?
Post.approved.where('lower(title) LIKE ?',"%#{search.downcase.strip}%")
else
@category = Category.find_by('id = ?',category_id.to_i)
@category.posts.approved.where('lower(title) LIKE ?',"%#{search.downcase.strip}%")
end
end
我知道如何为诸如验证和关联之类的简单事情编写测试,但是我仍然不知道如何为此类方法编写测试。任何帮助表示赞赏。
解决方法
您可以创建一些测试数据:
let!(:post_1) { Post.create(title: 'some example title') }
let!(:post_2) { Post.create(title: 'another title') }
并确认您的搜索返回了各种搜索字词的正确记录,例如:
expect(Post.search('example')).to contain_exactly(post_1)
expect(Post.search('EXAMPLE')).to contain_exactly(post_1)
expect(Post.search('title')).to contain_exactly(post_1,post_2)
expect(Post.search('foo')).to be_empty
(假设search
是Post
的一种方法)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。