我想用RSPEC測試我的API控制器。控制器中的操作具有我想要存根/模擬的服務。但我得到了錯誤:RSPEC錯誤的控制器測試不執行
Failure/Error: expect(Api::V1::PaymentsController).to receive(:init_alias).and_return(svc) Api::V1::PaymentsController does not implement: init_alias
這裏我的測試:
let(:alias_svc) { instance_double(AliasService) }
describe 'POST /payment/card' do
it 'returns urls (return, success, fail)' do
expect(Api::V1::PaymentsController).to receive(:init_alias).and_return(alias_svc)
expect(alias_svc).to receive(:insert)
post '/payment/card'
end
end
而且控制器:
module Api
module V1
class PaymentsController < ApiController
before_action :init_alias, only: [:register_card]
# POST /payment/card
def register_card
@url = @svc.insert current_user
end
private
def init_alias
@svc = AliasService.new
end
end
end
end
編輯:
我試圖刪除第一行( expect(Api :: V1 :: PaymentsController).to接收(:init_alias).and_return(alias_svc ))但我得到了
Failure/Error: expect(svc).to receive(:insert) (InstanceDouble(AliasService) (anonymous)).insert(*(any args)) expected: 1 time with any arguments received: 0 times with any arguments
它幾乎可以工作,謝謝。但我仍然有第二個錯誤 – Xero
將'alias_svc'傳遞給'instance_variable_set'。我已經更新了答案。 – yzalavin