2010-03-01 14 views
26

Sto tentando di prevedere un errore in un test rspec.Aspettarsi errori nei test rspec

lambda {Participant.create!({:user_id => three.id, :match_id => match.id, :team => 1})}.should raise_error StandardError 

Per ora sto usando solo StandardError per assicurarsi che funzioni.

1) StandardError in 'Participant should never allow more participants than players'. 
    This game is already full. Cannot add another player. 
/home/josiah/Projects/Set-Match/app/models/participant.rb:12:in `do_not_exceed_player_count_in_match' 
./spec/models/participant_spec.rb:24: 

Getta chiaramente l'errore, ma il mio test fallisce ancora.

Pensieri?

risposta

34

La sintassi è corretta. Per eseguire il debug di questo, semplificare per assicurarsi che le specifiche siano codificate correttamente.

it "should raise an error" do 
    lambda {raise "boom"}.should raise_error 
end 

E quindi aggiungere più dettagli fino a quando non si rompe.

lambda {raise "boom"}.should raise_error(RuntimeError) 
lambda {raise StandardError.new("boom")}.should raise_error(StandardError) 
+0

Grazie per la punta. –

5

ho dovuto lottare con gli stessi sintomi:

def boom 
    raise "boom" 
end 
boom.should raise_error 

La prova di cui sopra non è riuscito perché raise_error richiede should di essere chiamato su un Proc (per motivi tecnici, suppongo). Così, avvolgendo una chiamata di metodo con un lambda funziona bene:

lambda { boom }.should raise_error 

Purtroppo, la documentazione non dice che in modo esplicito e non c'è RSpec Eccezione che rivela questo comportamento. C'è uno two year old ticket per quello.

+2

"boom.should raise_error" fallisce perché il braccio viene valutato appena prima di eseguire "dovrebbe"; lambda, d'altra parte, è chiamato dal "dovrebbe" stesso. – grilix

45

Da qualche tempo, ma almeno in RSpec 2.5, è possibile utilizzare

expect {raise 'boom'}.to raise_error(RuntimeError, /boom/)