2009-02-06 77 views
3

我想了解爲什麼這個測試失敗。 (我對測試很陌生。)我使用了內置的Rails測試框架,並添加了Shoulda gem。爲什麼這個Rails控制器測試失敗?

測試:

require 'shoulda' 

context "on GET to :new" do 

    setup do 
    get(:new) 
    end 

    should_render_template :new 
    should_not_set_the_flash 

end 

失敗:

1) Failure: 
test: on GET to :new should render template :new. (SessionsControllerTest) 
[/usr/local/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.0.6/lib/shoulda/controller /macros.rb:220:in `__bind_1233882600_699194' 
/usr/local/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.0.6/lib/shoulda/context.rb:254:in `call' 
/usr/local/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.0.6/lib/shoulda/context.rb:254:in `test: on GET to :new should render template :new. ' 
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/testing/setup_and_teardown.rb:94:in `__send__' 
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/testing/setup_and_teardown.rb:94:in `run']: 
expecting <"new"> but rendering with <""> 

2 tests, 2 assertions, 1 failures, 0 errors 

但如果我app.get '/sessions/new'控制檯上運行它,它工作正常,沒有錯誤。

而「new」模板按預期在瀏覽器中呈現。

我正在使用Haml。也許這是造成問題的原因。我的模板被稱爲「new.html.haml」。

回答

8

失敗說沒有模板被渲染。儘量確保你不被重定向與

should_respond_with :success 

,並斷言@ response.body的內容只是爲了看看有什麼被送回

# This will fail but should give you some clue about what was sent back. 
should "sent something back in the body" do 
    assert_match 'boohooo', @response.body 
end 

您也可以斷言一個特定的模板,所以你可以給它一個鏡頭,太:

should_render_template "new.html.haml" 

不過,我不疑HAML是你的問題的原因。

+0

謝謝。你建議你調用assert_match來解決它。我已經忘記了之前的一個過濾器搞亂了事情。 – Ethan 2009-02-06 07:07:59

0

我和Shoulda,Clearance和Rails 2.3.2有類似的問題。我想我通過修改shoulda和clearance如何使用'assert_template'來解決這個問題。顯然,Rails中有一個與此相關的開放漏洞。

請參閱此主題以獲取更多信息和變更的差異(Clearance和Shoulda中的一行更改)。

http://groups.google.com/group/shoulda/browse_thread/thread/8c0a66c80ff4fd76

相關問題