2011-03-27 7 views
7

RSpec을 사용하여 Ruby를 테스트 할 수 있습니까? 이와 같이RSpec을 사용하여 경고 테스트

:

class MyClass 
    def initialize 
    warn "Something is wrong" 
    end 
end 

it "should warn" do 
    MyClass.new.should warn("Something is wrong") 
end 

답변

15
warn

마다 객체에 포함 Kernel에서 정의된다. 당신이 초기화하는 동안 경고를 제기하지 않은 경우, 당신은이 같은 경고를 지정할 수 있습니다 :

obj = SomeClass.new 
obj.should_receive(:warn).with("Some Message") 
obj.method_that_warns 

initialize 방법에서 제기 된 경고를 Spec'ing하는 것은 매우 복잡하다. 수행해야하는 경우 가짜 IO 개체를 $stderr으로 바꿔서 검사 할 수 있습니다. 그냥 정확히 문제 해결 사용자 기대와 좋은 기사가있다

class MyClass 
    def initialize 
    warn "Something is wrong" 
    end 
end 

describe MyClass do 
    before do 
    @orig_stderr = $stderr 
    $stderr = StringIO.new 
    end 

    it "warns on initialization" do 
    MyClass.new 
    $stderr.rewind 
    $stderr.string.chomp.should eq("Something is wrong") 
    end 

    after do 
    $stderr = @orig_stderr 
    end 
end 
+0

이 오히려 SomeClass'보다 SomeClass.allocate''할 수 없습니다 : 414,이, 나는 CustomMatchers을 포함 한 후 지금

require 'rspec' require 'stringio' module CustomMatchers class HasWarn def initialize(expected) @expected = expected end def matches?(given_proc) original_stderr = $stderr $stderr = StringIO.new given_proc.call @buffer = $stderr.string.strip @expected.include? @buffer.strip ensure $stderr = original_stderr end def supports_block_expectations? true end def failure_message_generator(to) %Q[expected #{to} get message:\n#{@expected.inspect}\nbut got:\n#{@buffer.inspect}] end def failure_message failure_message_generator 'to' end def failure_message_when_negated failure_message_generator 'not to' end end def has_warn(msg) HasWarn.new(msg) end end 

당신이 따를 때이 기능을 사용할 수있는 사용자 정의 정규의 has_warn을 내 솔루션 정의한다 .new', 그리고 should_receive를주고 초기화를 실행 하시겠습니까? –

+0

'initialize'에서 경고를 위해 사용한 다른 접근법은'Kernel.warn'을 ('warn'이 아닌)'Kernel.warn'을 명시 적으로 호출하는 것입니다. 커널에서 호출 할 필요는 없습니다. 일부 전역에서 호출 되어야만 인스턴스화 전에 should_receive를 설정할 수 있습니다. –

4

예 후 복원해야합니다 : http://greyblake.com/blog/2012/12/14/custom-expectations-with-rspec/ 그래서

이 싶습니다 그에

expect { MyClass.new }.to write("Something is wrong").to(:error) 

자료를 당신은 당신이 이것 같이 그것을 사용하기 위하여 당신 자신의 기대를 창조 할 수있다 :

expect { MyClass.new }.to warn("Something is wrong") 
+2

이것은 대단한 멋진 답변이지만, 기사가 다운 될 경우를 대비해 기사의 대량을 올려 놓는 것이 좋습니다. – sunnyrjuneja

0
expect{ MyClass.new }.to has_warn("warning messages") 
관련 문제