RAIRS RSPEC-如何测试是否在另一个服务中调用服务
在编写测试时,我停止尝试在另一个服务中测试服务。在这种情况下,我可能应该检查是否已调用服务,因为它已经在其他地方进行了测试。我在互联网上进行了一些研究,发现了home_received
,但我不知道如何在示例中使用它。
check_service.rb
Class CheckService
def initialize(params)
@params = params
end
def self.call(params)
new(params).call
end
def call
CheckUser.call(params[:user_id])
end
end
check_service_spec.rb
...
describe 'call' do
let(:result) { CheckService.call(params) }
let(:params) { { user_id: "100" } }
let(:check_user) { instance_double(CheckUser) }
before do
allow(check_user).to receive(:call).and_return(true)
end
it do
result
expect(check_user).to have_received(:call)
end
end
...
我正在尝试这样的事情(这很简单),但是我会遇到错误:
(InstanceDouble(CheckUser) (anonymous)).call(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
是否有任何测试情况的选项?
While writing tests, I stopped at trying to test Service in another Service. In such a situation, I should probably just check if Service has been called because it has already been tested elsewhere. I did a little research on the Internet and found something like have_received
but I have no idea how to use it in my example.
check_service.rb
Class CheckService
def initialize(params)
@params = params
end
def self.call(params)
new(params).call
end
def call
CheckUser.call(params[:user_id])
end
end
check_service_spec.rb
...
describe 'call' do
let(:result) { CheckService.call(params) }
let(:params) { { user_id: "100" } }
let(:check_user) { instance_double(CheckUser) }
before do
allow(check_user).to receive(:call).and_return(true)
end
it do
result
expect(check_user).to have_received(:call)
end
end
...
I was trying something like this (it's simple example), but I get error:
(InstanceDouble(CheckUser) (anonymous)).call(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
Is there any option to test situation I presented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短的anwser
替代方案,
我认为一种更好的测试方法是使用di(依赖项注入),因此您将检查用户作为依赖性访问服务器进行检查。我也更喜欢在
it
块中写下整个测试!一篇博客文章,以了解有关 - > https:// .testdouble.com/posts/2018-05-17-do-we-need-dependency-injection-in-ruby/
Short anwser
Alternative
I think a better way to test this is to use DI (Dependency Injection), so you pass CheckUser as a dependency to CheckService. I prefer to write the whole test inside the
it
block too!A blog post to read more about -> https://blog.testdouble.com/posts/2018-05-17-do-we-need-dependency-injection-in-ruby/