简体   繁体   English

如何为类方法编写测试 Rspec?

[英]How to write test Rspec for class method?

I'm new to RSpec so this really give me a headache.我是 RSpec 的新手,所以这真的让我很头疼。 I have a search by keyword or by category in Post model:我在 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

I know how to write test for easy thing like validations and associations, but I still can not figure how to write test for this class method.我知道如何为诸如验证和关联之类的简单事情编写测试,但我仍然无法弄清楚如何为此类方法编写测试。 Any help is appreciated.任何帮助表示赞赏。

You could create some test data:您可以创建一些测试数据:

let!(:post_1) { Post.create(title: 'some example title') }
let!(:post_2) { Post.create(title: 'another title') }

And validate that your search returns the correct records for various search terms, eg:并验证您的搜索是否返回了各种搜索词的正确记录,例如:

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

(assuming search is a method of Post ) (假设searchPost一种方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM