2013-05-02 3 views
2

테스트 용으로 최근에 RSpec matcher의 일부를 DSL 대신 클래스 형식을 사용하도록 이동했습니다. 이 양식에있을 때 쉽게 체이닝 동작을 얻는 방법이 있습니까?Rspec 사용자 지정 Matcher를 연결

예.

class BeInZone 
    def initialize(expected) 
    @expected = expected 
    end 
    def matches?(target) 
    @target = target 
    @target.current_zone.eql?(Zone.new(@expected)) 
    end 
    def failure_message 
    "expected #{@target.inspect} to be in Zone #{@expected}" 
    end 
    def negative_failure_message 
    "expected #{@target.inspect} not to be in Zone #{@expected}" 
    end 
    # chain methods here 
end 

많은 감사

+0

연결할 수있는 연결 식 메서드 호출의 예를 들려 줄 수 있습니까? –

답변

3

는 일반적으로 self을 반환해야 체인의 이름으로 새로운 방법을 추가합니다. 일반적으로 제공된 체인 상태를 저장합니다. 그런 다음 matches? 메서드를 업데이트합니다. 이 상태는 다양한 출력 메시지 메소드에도 사용될 수 있습니다. 그래서 예를 들어

:

class BeInZone 
    # Your code 

    def matches?(target) 
    @target = target 

    matches_zone? && matches_name? 
    end 

    def with_name(name) 
    @target_name = name 
    self 
    end 

    private 
    def matches_zone? 
    @target.current_zone.eql?(Zone.new(@expected)) 
    end 

    def matches_name? 
    true unless @target_name 

    @target =~ @target_name 
    end 
end 

그런 다음이 기능을 사용하려면이 작품 expect(zoneA_1).to be_in_zone(zoneA).with_name('1')

이유는 당신이 중 하나 should 또는 expect(object).to 방법으로 전달하는 객체를 구축하고 있다는 점이다. 그런 다음이 메소드는 제공된 객체에서 matches?을 호출합니다.

따라서 다른 루비 코드 인 puts "hi there".reverse.upcase.gsub('T', '7')과 다를 바 없습니다. 여기에 문자열 "hi there"이 당신의 일치 프로그램이고 연결된 메소드가 호출되어 gsub에서 반환 된 최종 객체를 puts으로 전달합니다.

내장 된 예상 change 일치 프로그램을 검토하는 것이 좋습니다.

+0

고맙습니다. matchers를 업데이트합니다. –

0

이 주제에 대한 자습서를 작성했습니다.
은 참조하십시오 www.danielcsite.com/rspec_custom_matchers
을 내가 자세히 및 사용자 정의 정규 클래스를 작성하고 여러 가지 방법을 체인의 방법으로 호출하는 두 방법을 스크린 샷으로 보여주는 튜토리얼.

관련 문제