我在我试图测试的方法中看到这样的代码:
service = if user_activator?
SomeService.new(subscription.user, cookies: cookies)
elsif sub_activator?
SomeOtherService.build(subscription: subscription, cookies: cookies)
end
我正在尝试将服务存根作为SomeService的一个实例,然后尝试查看它是否收到一个包含如下代码的方法:
expect(some_service_instance).to receive(:activate).with(hash_including(
app_context: app_context,
cookies: cookies,
subscription: subscription
))
但有没有办法将局部变量存根为UserActivationService的实例?
以下是我认为可行的一些方法?
首先,我应该将条件局部变量集提取到这样的方法中(这感觉很可疑):
def service
if some_service_activator?
SomeService.new(subscription.user, cookies: cookies)
elsif sub_activator?
SomeOtherService.build(subscription: subscription, cookies: cookies)
end
end
然后我可以做到:
let(:some_service_instance) { SomeService.new(subscription.user, cookies: cookies) }
allow(<something that returns an instance of the class I am testing>).to receive(:service) { some_service_instance }
然后
expect(some_service_instance).to receive(:activate).with(hash_including(
app_context: app_context,
cookies: cookies,
subscription: subscription
))
这是犹太人吗?
答案 0 :(得分:-1)
假设这一切都在控制器内发生,我想你想使用@controller
变量。
let(:user_activation_service_instance) { UserActivationService.new(subscription.user, cookies: cookies) }
allow(@controller).to receive(:service) { user_activation_service_instance }