如何测试创建实例的类方法?

发布于 2025-01-13 20:36:13 字数 175 浏览 1 评论 0原文

我有这样一个类:

class BaseService
  def self.call(*args)
    new(*args).call
  end
end

我需要测试 #self.call 使用给定参数创建新实例并向其发送 :call 消息。 怎么可能呢? 提前致谢!

I have such a class:

class BaseService
  def self.call(*args)
    new(*args).call
  end
end

I need to test that #self.call creates new instance with given arguments and sends it :call message.
How is it possible?
Thanx in advance!

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

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

发布评论

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

评论(1

深海里的那抹蓝 2025-01-20 20:36:13

我会执行以下操作

let(:arguments) { [:foo, :bar] }
let(:base_service) { instance_double('BaseService') } 

before do 
  allow(BaseService).to receive(:new).with(*arguments).and_return(base_service)
  allow(base_service).to receive(:call).with(no_args)
end

it "does the expected thing" do
  BaseService.call(*arguments)

  expect(BaseService).to have_received(:new).with(*arguments).once
  expect(base_service).to have_received(:call).once
end

另一个(也许更好)选项可能是测试 BaseService.call(*arguments) 是否具有预期的输出或副作用。但是因为您没有编写 new(*args).call 实际执行的操作,所以我无法对此提出建议。

I would do the following

let(:arguments) { [:foo, :bar] }
let(:base_service) { instance_double('BaseService') } 

before do 
  allow(BaseService).to receive(:new).with(*arguments).and_return(base_service)
  allow(base_service).to receive(:call).with(no_args)
end

it "does the expected thing" do
  BaseService.call(*arguments)

  expect(BaseService).to have_received(:new).with(*arguments).once
  expect(base_service).to have_received(:call).once
end

Another (and perhaps better) option might be to test that BaseService.call(*arguments) has the expected output or side-effects. But because you didn't write what new(*args).call actually does I cannot make a suggestion for that.

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