【发布时间】:2016-08-19 01:04:15
【问题描述】:
RSpec 中是否有任何匹配器来检查一个类是否用参数实例化?
类似it { is_expected.to respond_to(:initialize).with(1).argument }
谢谢!
【问题讨论】:
标签: ruby oop rspec tdd rspec-expectations
RSpec 中是否有任何匹配器来检查一个类是否用参数实例化?
类似it { is_expected.to respond_to(:initialize).with(1).argument }
谢谢!
【问题讨论】:
标签: ruby oop rspec tdd rspec-expectations
The respond_to matcher that you give as an example exists, with the exact syntax that you give.
但是,您需要测试.new 方法,而不是.initialize 方法,因为.initialize 是私有的。
class X
def initialize(an_arg)
end
end
describe X do
describe '.new'
it "takes one argument" do
expect(X).to respond_to(:new).with(1).argument
end
end
end
【讨论】:
我不能 100% 确定这是否是您要问的?默认情况下,如果该类需要参数并且您实例化不正确,它将引发 ArgumentError。
require 'rspec'
class Test
def initialize(var)
end
end
RSpec.describe do
describe do
it do
expect(Test).to receive(:new).with('testing')
Test.new('test')
end
end
end
或者,您可以在参数上使用 attr_reader 并比较 instance_variables。
【讨论】: