如何使用RSPEC调用其他方法来测试非静态方法

发布于 2025-02-08 19:08:05 字数 482 浏览 2 评论 0原文

我正在尝试测试一种通过另一种方法调用的方法。 我不想测试其他方法的作用,因为这是一个单独的单元测试。

假设我有类似的东西:

class MyService
    def method_a
      a = 1
      b = method_b
      
      return a + b
    end

    def method_b
      return 2
    end

end

现在,我想测试Method_a-我想验证Method_b已执行。

我知道,如果这些方法是静态的,这应该有效。但就我而言,这不是静态的。

allow(MyService).to receive(:method_b)

我一直遇到这个错误: myService不实现method_b 我知道这是因为该方法不是静态的,但是我在文档中找不到任何适合我用例的方法。

I'm trying to test a method being called by another method.
I don't want to test what the other method do, because this is a separate unit test.

so let's say I have something like:

class MyService
    def method_a
      a = 1
      b = method_b
      
      return a + b
    end

    def method_b
      return 2
    end

end

Now, I want to test method_a - I want to verify that method_b was executed.

I know that this should work if the methods were static. But in my case, it's not static.

allow(MyService).to receive(:method_b)

I keep getting this error:
MyService does not implement method_b
And I understand that's because the method is not static, but I can't find anything in the documentation that fit my use case.

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

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

发布评论

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

评论(1

迟月 2025-02-15 19:08:05

我认为主要问题是您期望将类方法称为而不是实例

describe MyService do
  it "should call method_b" do
    expect(subject).to receive(:method_b).and_return(2)
    subject.method_a
  end
end

# P.S. it's the same as:

describe MyService do
  it "should call method_b" do
    service = MyService.new # instead of MyService.new you can also write described_class.new
    expect(service).to receive(:method_b).and_return(2)
    service.method_a
  end
end

I think main problem problem is that you expecting for class method to be called and not instance

describe MyService do
  it "should call method_b" do
    expect(subject).to receive(:method_b).and_return(2)
    subject.method_a
  end
end

# P.S. it's the same as:

describe MyService do
  it "should call method_b" do
    service = MyService.new # instead of MyService.new you can also write described_class.new
    expect(service).to receive(:method_b).and_return(2)
    service.method_a
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文