繁体   English   中英

控制器中对象方法调用的Rspec测试

[英]Rspec test of the object method call in controller

我想测试控制器创建和更新操作在MentionService实例上调用流程方法。

在控制器中我有MentionService.new(post).process

这是我目前的规格:

it "calls MentionService if a post has been submitted" do
  post = Post.new(new_post_params)
  mention_service = MentionService.new(post)
  expect(mention_service).to receive(:process)
  xhr(:post, :create, company_id: company.id, remark: new_post_params)
end

在控制器动作中,我有:

def create
  ...
  # after save
  MentionService.new(@remark).process
  ...
end

我得到的是:

expected: 1 time with any arguments
received: 0 times with any arguments

有任何想法吗? 谢谢。

问题是您要在测试中创建一个新实例,并希望该实例接收:process而不起作用。

尝试使用以下代码片段:

let(:service) { double(:service) }

it "calls MentionService if a post has been submitted" do
  expect(MentionService).to receive(:new).with(post).and_return(service)
  expect(service).to receive(:process)
  xhr(:post, :create, company_id: company.id, remark: new_post_params)
end

您需要告诉MentionService类接收:new并返回一个模拟对象,该对象将接收:process 在这种情况下,您知道调用顺序已成功。

如果您对自己提供模拟对象不感兴趣,还可以将期望修改为:

expect_any_instance_of(MentionService).to receive(:process)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM