简体   繁体   English

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

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

I want to test that a controller create and update actions call a process method on the MentionService instance. 我想测试控制器创建和更新操作在MentionService实例上调用流程方法。

In controller I have MentionService.new(post).process 在控制器中我有MentionService.new(post).process

This is my current spec: 这是我目前的规格:

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

In the controller actions I have: 在控制器动作中,我有:

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

What I get is: 我得到的是:

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

Any ideas? 有任何想法吗? Thanks. 谢谢。

The problem is that you're creating a new instance in your test and expect that instance to receive :process which will not work. 问题是您要在测试中创建一个新实例,并希望该实例接收:process而不起作用。

Try playing around with this snippet: 尝试使用以下代码片段:

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

You need to tell your MentionService class to receive :new and return a mock object, which will receive :process . 您需要告诉MentionService类接收:new并返回一个模拟对象,该对象将接收:process If that is the case, you know the call sequence succeeded. 在这种情况下,您知道调用顺序已成功。

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

expect_any_instance_of(MentionService).to receive(:process)

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

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