[英]Rspec: how to test Service Object method “call” which is called in Controller action create?
[英]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.