【问题标题】:How to write test Rspec for class method?如何为类方法编写测试 Rspec?
【发布时间】:2020-10-15 08:46:27
【问题描述】:

我是 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

我知道如何为验证和关联等简单的事情编写测试,但我仍然不知道如何为这个类方法编写测试。任何帮助表示赞赏。

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    您可以创建一些测试数据:

    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
    

    (假设searchPost的方法)

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 2017-08-23
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多