RSpec 控制器测试-空白响应

在使用 RSpec 测试控制器时,我遇到了一个问题—— response. body 调用总是返回一个空字符串。在浏览器中,所有的渲染都是正确的,黄瓜特性测试似乎也是正确的,但是 RSpec 每次都失败了。

对响应对象的其他期望,如 response.should render_template('index')通过没有任何问题。

你们中有人以前遇到过这个问题吗? 也许可以通过其他方式获得响应 html?

至于版本,Rails 2.1.0,RSpec 1.2.7。

29689 次浏览

By default, rspec-rails hacks into Rails to prevent it from actually rendering view templates. You should only test the behavior of your actions & filters your controller tests, not the outcome of template rendering — that's what view specs are for.

However, if you wish to make your controller specs render templates as the app normally would, use the render_views directive:

describe YourController do
render_views
...
end

As I worked with a similar problem (that led me to this question), it occurred to me that there are different ways to skin the same cat. In other words, rather than checking for the body text, you might be able to check the content of the flash.

response.body.should =~ /Invalid email or password/

might be an equivalent check to:

flash[:alert].should == "Invalid email or password"

To me the latter seems a bit more flexible as it will run either way, but it may not be appropriate in all cases.

Cheers,

John

RSpec 2+: If you want to check end to end - url to response body - use a request spec instead of a controller spec.

By default, RSpec-rails configuration disables rendering of templates for controller specs

One of the ways to fix this is by making sure to enable the render_views setting in your rails_helper.rb file. In this way, you make it able to work globally in all your tests.

RSpec.configure do |config|
config.render_views
end

Or use render_views declaration an individual group:

describe User do
render_views
end

You can read more about this here.