我有一组服务和子模块如下:
class Calculate::Document
def self.build
new
end
def initialize
@country_codes = [1,2,3]
end
def call(document)
...
@document = document
calculate_by_country
end
private
def calculate_by_country
#define by country
location = (@country_codes.include? @document.country_code) ? @document.country_code : 'Generic'
#Build dynamic class name
klass = ('Calculate::Document::Countries::' + location.titleize + '::Base').constantize
#call dynamic class
@document = klass.build.call(@document)
end
end
class Calculate::Document::Countries::Usa::Base
def self.build
new(
...
)
end
def initialize(...)
....
end
def call(document)
@document = document
.....
return @document
end
end
我用rspec测试上面的内容如下:
describe Calculate::Document do
before do
@service = Calculate::Document.build
@document = FactoryGirl.build(:document, country_code: 'usa')
end
context "unit tests" do
it "calls calculate_by_country" do
calculate_by_country = instance_double("PayrollService::CalculatePayslip::Countries::Usa::Base", call: nil)
@service.call(@document)
expect(calculate_by_country).to have_received(:call).with(@document)
end
end
end
基本上我试图测试服务是否调用动态命名的子模块,并且子模块返回一个具有so&so属性的对象。代码有效,但测试没有。
如何使用rspec测试动态命名的类?
答案 0 :(得分:1)
您的double
不是call
中实例化的对象,请尝试:
expect_any_instance_of(PayrollService::CalculatePayslip::Countries::Usa::Base).to receive(:call).with(@document)
@service.call(@document)