Rspec 显示与浏览器不同的状态代码 [英] Rspec shows different status code than browser
问题描述
我正在尝试为 Rails 中的自定义重定向页面编写 rspec 测试.基本上,我在 routes.rb 中有一个通配符匹配,用于获取页面名称,以及Pages"控制器中的 show 方法,用于检查该名称的部分是否存在.如果它没有找到匹配的部分,它会呈现一个 404 页面并将状态设置为 404.所有这些都在浏览器中工作,但是 rspec 将其视为 200OK"响应,而不是 404.
I'm trying to write an rspec test for a custom redirect page in Rails. Basically I've got a wildcard match in routes.rb that gets a page name, and a show method in a "Pages" controller that checks if a partial by that name exists. If it doesn't find a matching partial, it renders a 404 page and sets the status to 404. All this works in the browser, however rspec sees it as a 200 "OK" response, not a 404.
代码:页面控制器显示方法(partial_exists?是我已经彻底测试过的私有方法,我可以使用测试日志验证 _missing.html.erb 在 rspec 运行时是否按预期呈现)
The code: Pages controller show method (partial_exists? is a private method that I've thoroughly tested, and I can verify using the test logs that _missing.html.erb is being rendered as expected when rspec runs)
def show
@page_name = params[:page_name].to_s.gsub(/\W/,'')
unless partial_exists?(@page_name)
render :partial => 'missing', :status => :not_found
end
end
routes.rb:
match '/' => 'pages#show', :page_name => 'index'
match '*page_name' => 'pages#show'
规格:
require 'spec_helper'
describe PagesController do
render_views
describe "get page name of request" do
it "should generate http success for a defined partial" do
visit '/'
response.should be_success
end
it "should give respond with the 404 missing page for an undefined partial" do
visit '/blahblahblah'
response.status.should be(404)
end
end
end
第一个测试按预期运行,并呈现状态代码为 200 的 _index.html.erb 部分.第二个测试呈现 _missing.html.erb(我已通过查看测试日志验证了这一点),但报告状态代码为 200,而不是预期的 404.当我在浏览器中运行它时,它会以状态码 404 呈现 _missing.html.erb.
The first test runs as expected, and renders _index.html.erb partial with a status code of 200. The second test renders _missing.html.erb (I've verified this by looking at the test logs), but reports a status code of 200, not 404 as expected. When I run it in the browser, it renders _missing.html.erb with a status code 404.
有什么想法吗?
推荐答案
您似乎将请求(功能)规范与控制器规范混淆了.visit
用于请求规范.对于控制器规范,您需要这样的东西:
It appears that you are confusing request (feature) specs with controller specs. visit
is for use in request specs. For a controller spec, you want something like this:
describe "get page name of request" do
it "should generate http success for a defined partial" do
get :index
response.should be_success
end
end
使用 get
或 post
以及适当的动作名称来测试控制器中的相应动作.
Use get
or post
along with the appropriate action name to test the corresponding action in the controller.
这篇关于Rspec 显示与浏览器不同的状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!