我有控制器中的方法是这样的:

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
有帮助吗?

解决方案

更改你的断言是

response.should be_redirect

至少,如果它是做正确的事:)

其他提示

我很困惑,为什么你的测试输出写着“ApiController调用test()方法......”当你的例子似乎是的TestController。我已经运行了几个我自己的例子,我似乎得到正确的结果。我建议您尝试Ruby调试(宝石红宝石调试)来诊断这一点。这样,你可以确认正确的代码被称为以及交互检查值。

根据定义,正在执行的控制器上的单元测试,因此不应该尝试看看有什么在响应中,只有正确的行动发生了,做的一切都是它应该做的事。测试响应的内容是一个集成测试像黄瓜的作业。

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

@response.should be_redirect
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top