有没有正确的方法来使用 is_a?有一个instance_double?
我有现实世界的代码,它执行以下操作:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会这样做:
I would do: