1

我有如下所示的控制器方法:

class TestController < ApplicationController
  def testAction
    render :json => { 'success'=>1 }.to_json
  end
end

当我在浏览器中加载这个动作时,我得到了我所期望的:{"success":1}

然而,当使用 RSpec 进行测试时,response.body给了我'<html><body>You are being <a href="https://test.host/test/testAction">redirected</a>.</body></html>'

我注意到我所有的控制器都发生了这种奇怪的重定向。如何阻止这种重定向的发生,以便对响应正文进行检查?

谢谢!

- - - - - - - - - - - - 编辑:

知道为什么会发生以下测试失败吗?

# app/controllers/test_controller.rb
def test
  flash[:notice] = 'test'
end

# spec/controllers/test_controller_spec.rb
describe TestController, "calling the test() method" do
  it "should set the flash notice" do
    put :test
    flash[:notice].should_not be_blank
  end
end

# result
'TestController calling the test() method should set the flash notice' FAILED
expected blank? to return false, got true
4

3 回答 3

0

将您的断言更改为

response.should be_redirect

至少,如果它做对了:)

于 2011-09-15T18:13:09.963 回答
0

当您的示例似乎适用于 TestController 时,我很困惑为什么您的测试输出显示“ApiController 调用 test() 方法...”。我已经运行了几个自己的示例,并且似乎得到了正确的结果。我建议尝试使用 Ruby 调试器 (gem ruby​​-debug) 来诊断这个问题。这样,您就可以确认正在调用正确的代码并以交互方式检查值。

于 2010-01-27T14:32:51.387 回答
-1

根据定义,您正在控制器上执行单元测试,因此不应该尝试查看响应中的内容,而只是发现正确的操作发生并完成了它应该做的一切。测试响应的内容是像 Cucumber 这样的集成测试的工作。

本质上,尝试断言控制器尝试了重定向。

@response.should be_redirect
于 2010-01-26T10:33:31.507 回答