2017-12-22 47 views
0

서비스 클래스가 HTTP 호출을 호스팅하고 작업 클래스가 데이터를 살균/패키지하고 서비스 클래스를 호출하여 외부 API와 통신하는 동작/서비스 기반 아키텍처를 사용하고 있습니다. . 설치가 잘 작동하지만 액션 클래스에 대한 mock을 설정하는 방법이 궁금합니다.RSpec을 사용하여 서비스 클래스를 인스턴스화하는 동작 클래스 테스트

# Service 
class UserService 
    def update_user user_id, data 
    # make request 
    end 
end 

# Action 
class UserUpdate 
    def initialize user_id, user_data 
    @id = user_id 
    @sanitized_data = user_data 
    end 

    def call 
    service = UserService.new 
    service.call(@id, @sanitized_data) 
    end 
end 

나는 문제없이 작업을 조롱 할 수 있지만, 내가 클래스 또는 인스턴스가 서비스를 두 번 사용하려고하면, 나는 오류를 얻을 예를 들면 다음과 같습니다 액션/서비스 쌍입니다. 여기 내 테스트는 지금까지의 :

it "should create an instance of Agent Service" do 
    agent_action_mock = class_double("AgentUpdate") 
    agent_service_mock = class_double("AgentService") 

    allow(agent_update_mock).to receive_message_chain(:new, :call) 
    allow_any_instance_of(AgentService).to receive_message_chain(:initialize, :update_user) 

    agenta_action_mock.new(99, { status: "Verified" }).call 
    expect_any_instance_of(AgentService).to receive(:initialize) 
end 

나에게 그물 어느 Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure } Exactly one instance should have received the following message(s) but didn't: initialize

나는 액션이 ​​서비스 클래스의 인스턴스를 생성하고이 방법의 호출하는지 테스트 할 수있는 방법입니다 궁금하네요 무엇?

+0

하지만 실제로 호출되고 있는지 확인하십시오. –

답변

0

테스트에 몇 가지 문제점이 있습니다. 먼저 모의 메소드를 호출합니다. 메서드를 call_original으로 설정하지 않으면 double의 모든 메서드가 스텁되고 아무 작업도 수행하지 않습니다. 따라서 double의 메서드를 호출하여 실제 동작을 트리거하는 방법은 없습니다.

두 번째로, 테스트가 끝날 때 예상을 사용하고 있으므로 기대치가 - have_received 인 스파이 형태를 사용해야합니다. 그렇지 않은 경우, expectation이 설정된 후 initialize를 호출합니다. 결코 발생하지 않습니다.