用RSPEC通过类方法来调用ActActiverEcord方法

发布于 2025-01-22 11:33:33 字数 848 浏览 1 评论 0原文

我很想做我想做的相当简单的事情。我有一个非常简单的类:

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

事情,但似乎无法弄清楚。

I'm stumped on what appears to be a fairly simple thing I'd like to do. I've got a pretty simple 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

I'd love to test that logic, so I simply need to assert that either find or find_by is called with the expected parameter. I've tried a couple of things:

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

and

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

Both result in

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

I must be doing something dumb here, but can't seem to figure it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逐鹿 2025-01-29 11:33:33

期望()。在执行操作之前,应定义()

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

阅读有关期望(...)。要接收(...) )

expect().to receive() should be define before we execute the operation.

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

Read more about expect(...).to receive(...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文