断言 ActiveRecord 方法是通过 class 方法和 RSpec 调用的

Assert ActiveRecord method is called through class method with RSpec

我对我想做的看似相当简单的事情感到困惑。我有一个非常简单的 class:

class User
  def self.find_by_search(query)
    query = query.to_s.strip

    if query.upcase.start_with?("USER")
      find(query)
    else
      find_by(name: "*#{query}*")
    end
  end
end

我很想测试这个逻辑,所以我只需要断言 findfind_by 是用预期参数调用的。我已经尝试了几件事:

User.find_by_search("USER0000")
expect(ActiveRecord::Base).to receive(:find)

User.find_by_search("USER0000")
expect(User).to receive(:find) # didn't really think this would work, but figured I'd try anyway

两者都导致

expected: 1 time with any arguments
received: 0 times with any arguments

我一定是在做什么蠢事,但似乎想不通。

expect().to receive()应该在我们执行操作之前定义。

expect(User).to receive(:find) 
User.find_by_search("USER0000")

阅读更多关于 expect(...).to receive(...)