有没有正确的方法来使用 is_a?有一个instance_double?

发布于 2025-01-11 16:17:19 字数 998 浏览 0 评论 0原文

我有现实世界的代码,它执行以下操作:

attr_reader :response
def initialize(response)
  @response = response
end

def success?
  response.is_a?(Net::HTTPOK)
end

和一个测试:

subject { described_class.new(response) }
let(:response) { instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200) }

it 'should be successful' do
  expect(subject).to be_success
end

这会失败,因为 # 不是 Net::HTTPOK< /code>

...我能够弄清楚如何解决这个问题的唯一方法是通过黑客攻击:

let(:response) do
  instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200).tap do |dbl|
    class << dbl
      def is_a?(arg)
        instance_variable_get('@doubled_module').send(:object) == arg
      end
    end
  end
end

我无法想象我是 ruby​​ 和 rspec 历史上唯一一个正在测试代码的人对测试进行内省double,因此认为必须有一种更好的方法来做到这一点——必须有一种方法可以让 is_a? 能够用 double 来解决这个问题?

I have real world code which does something like:

attr_reader :response
def initialize(response)
  @response = response
end

def success?
  response.is_a?(Net::HTTPOK)
end

and a test:

subject { described_class.new(response) }
let(:response) { instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200) }

it 'should be successful' do
  expect(subject).to be_success
end

This fails because #<InstanceDouble(Net::HTTPOK) (anonymous)> is not a Net::HTTPOK

... The only way I have been able to figure out how to get around this is with quite the hack attack:

let(:response) do
  instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200).tap do |dbl|
    class << dbl
      def is_a?(arg)
        instance_variable_get('@doubled_module').send(:object) == arg
      end
    end
  end
end

I can't imagine that I am the only one in the history ruby and rspec that is testing code being that performs introspection on a test double, and therefore think there has got to be a better way to do this-- There has to be a way that is_a? just will work out the box with a double?

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

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

发布评论

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

评论(1

仙女 2025-01-18 16:17:19

我会这样做:

let(:response) { instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200) }
before { allow(response).to receive(:is_a?).with(Net::HTTPOK).and_return(true) }

I would do:

let(:response) { instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200) }
before { allow(response).to receive(:is_a?).with(Net::HTTPOK).and_return(true) }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文