gpt4 book ai didi

ruby-on-rails - 如何测试渲染状态 : 404 with Rails4 and RSpec when using rescue_from

转载 作者:行者123 更新时间:2023-12-03 12:07:49 26 4
gpt4 key购买 nike

我有一个带有“PagesController”的 Rails4 应用程序。

当找不到页面时,show-method 会引发自定义异常“PageNotFoundError”。

在我定义的 Controller 之上rescue_from PageNotFoundError, with: :render_not_foundrender not foundPagesController 的私有(private)方法看起来像:

def render_not_found
flash[:alert]=t(:page_does_not_exists, title: params[:id])
@pages = Page.all
render :index, status: :not_found #404
end

开发模式下的 rails-log 显示:
Started GET "/pages/readmef" for 127.0.0.1 at 2013-08-02 23:11:35 +0200
Processing by PagesController#show as HTML
Parameters: {"id"=>"readmef"}
..
Completed 404 Not Found in 14ms (Views: 12.0ms)

所以,到目前为止,它连接了我的 :status => :not_found 作品。

当我做 curl -v http://0.0.0.0:3000/pages/readmef curl 日志
curl -v http://localhost:3000/pages/readmef
* About to connect() to localhost port 3000 (#0)
* Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /pages/readmef HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:3000
> Accept: */*
>
< HTTP/1.1 404 Not Found
< X-Frame-Options: SAMEORIGIN

但是使用 RSpec 进行的以下测试失败:
 it 'renders an error if page not found' do
visit page_path('not_existing_page_321')
expect(response.status).to eq(404)
within( '.alert-error' ) do
page.should have_content('Page not_existing_page_321 doesn\'t exist')
end
end

1) PagesController renders an error if page not found
Failure/Error: expect(response.status).to eq(404)

expected: 404
got: 200

一切看起来都很好,甚至 test.log 说 404
$ tail -f log/test.log
Started GET "/pages/not_existing_page_321" for 127.0.0.1 at 2013-08-03 09:48:13 +0200
Processing by PagesController#show as HTML
Parameters: {"id"=>"not_existing_page_321"}
Rendered pages/_page.haml (0.8ms)
Rendered layouts/_navigation.haml (0.6ms)
Rendered layouts/_messages.haml (0.2ms)
Rendered layouts/_locales.haml (0.3ms)
Rendered layouts/_footer.haml (0.6ms)
Completed 404 Not Found in 6ms (Views: 4.5ms)

我尝试了不同的服务器、WebRICK、Thin、 unicorn 。在开发和生产模式下,一切都按预期工作。即使 test.log 是正确的,但测试失败。

谁能告诉我为什么测试显示 200 而不是 404?

最佳答案

RSpec 3+ 的另一种方法是测试异常:

it 'responds with a 404 if the page is not found' do
expect { get(:show, id: 'bad_id') }.to raise_error(ActionController::RoutingError)
end

关于ruby-on-rails - 如何测试渲染状态 : 404 with Rails4 and RSpec when using rescue_from,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18026598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com