2011-02-09 5 views
10

저는 작은 루비 프로그램을 작성하면서 TDD를 배우고 있습니다. 다음 클래스가 있습니다 :Rspec이 작동하지 않거나 레이즈를 올리지 않습니까?

class MyDirectory 
    def check(dir_name) 
    unless File.directory?(dir_name) then 
     raise RuntimeError, "#{dir_name} is not a directory" 
    end 
    end 
end 

그리고이 rspec 테스트로 테스트하려고합니다.

describe MyDirectory do 
    it "should error if doesn't exist" do 
    one = MyDirectory.new 
    one.check("donee").should raise_exception(RuntimeError, "donee is not a directory") 
    end 
end 

rspec 출력에서 ​​잘못된 점을 이해하지 못합니다.

Failures: 

    1) MyDirectory should error if doesn't exist 
    Failure/Error: one.check("donee").should raise_error(RuntimeError, "donee is not a directory") 
    RuntimeError: 
     donee is not a directory 
    # ./lib/directory.rb:4:in `check' 
    # ./spec/directory_spec.rb:9:in `block (2 levels) in <top (required)>' 

나는 이것이 실종 된 것처럼 보이기를 바라지 만, 나는 그것을보고 있지 않습니다.

답변

33

예외를 확인하려면 람다를 사용하여 테스트를 분리해야합니다. 예외가 발생하면 예외가 발생합니다.

lambda {one.check("donee")}.should raise_error(RuntimeError, "donee is not a directory") 

편집 : 사람들은 여전히이 답변을 사용하기 때문에, 여기 RSpec에 3 할 것입니다 다음 구문이 옵션 블록을 취 기대 때문에

expect{one.check("donee")}.to raise_error(RuntimeError, "donee is not a directory") 

람다가 더 이상 필요하지 않습니다.

+0

완벽하게 작동합니다. 감사합니다. – gdziengel

+2

'expect {...}. to '대신'expect (...). to'를 사용했는데이 답변으로 마침내 실수를 찾는데 도움이되었습니다! –

+0

블록을 사용하는 대신 괄호를 사용하면 예외가 발생합니다. https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers 예외가 예상되는 경우 블록 구문을 사용해야합니다. –

관련 문제