assert_redirected_to用法?

时间:2012-10-23 03:56:43

标签: ruby-on-rails testunit

刚开始使用Test::Unit,但在确定重定向测试时遇到问题:

  test "should destroy line_item" do
    assert_difference('LineItem.count', -1) do
      delete :destroy, id: @line_item
    end

    assert_redirected_to controller: 'carts', action: 'show'
  end

会抛出以下错误:

Failure: Expected response to be a redirect to <http://test.host/carts/980190962> but was a redirect to <http://test.host/carts/980190963>.
test_should_destroy_line_item(LineItemsControllerTest)
test/functional/line_items_controller_test.rb:47:in `block in <class:LineItemsControllerTest>'

docs说明以下内容:

assert_redirected_to(options = {},message = nil)public

断言传入的重定向选项与最新操作中调用的重定向匹配。这个匹配可以是部分的,这样assert_redirected_to(:controller =&gt;&#34; weblog&#34;)也将匹配redirect_to的重定向(:controller =&gt;&#34; weblog&#34;,:action =&gt; ;&#34;显示&#34;)等等。

但是assert_redirected_to controller: 'carts'会导致更彻底的失败:

Failure: Expected response to be a redirect to <http://test.host/carts> but was a redirect to <http://test.host/carts/980190963>.
test_should_destroy_line_item(LineItemsControllerTest)

如果文件正确,我错过了什么?如果不是,我有什么选择来测试重定向,而不管匹配的ID是什么?

1 个答案:

答案 0 :(得分:0)

assert_redirected_to的文档似乎并不完全正确,但问题的一部分与设置阶段(创建@line_item时)的cart_id不同有关它被摧毁的阶段。因此,解决方法是修改夹具/控制器,使其在销毁时具有相同的cart_id。它并没有解决assert_redirected_to的实际问​​题,但至少测试将通过。