【问题标题】:How to test render :file => 'public/404.html' in Rspec 2?如何在 Rspec 2 中测试渲染:file => 'public/404.html'?
【发布时间】:2012-07-12 03:15:37
【问题描述】:

我在一个动作中有以下代码:

render :file => 'public/404.html' and return

这在浏览器中运行良好。我编写了以下 rspec 示例来对此进行测试:

  it "renders 404" do
    get :new
    response.should render_template('public/404.html')
  end

运行此示例会导致以下错误:

 Failure/Error: response.should render_template('public/404.html')
   Expected block to return true value.

我也尝试过response.should render_template(:file => 'public/404.html'),但这也会导致错误。

我应该如何测试这个?

【问题讨论】:

    标签: ruby-on-rails testing rspec


    【解决方案1】:

    如果要显示 404 页面,记得设置状态码。这也是我要测试的:it { should respond_with :not_found }

    除了直接渲染 public/404 之外,还有更好的方法来做到这一点。看看这个答案:How to redirect to a 404 in Rails?

    【讨论】:

    • 如果它是任何其他页面而不是 404.html(或 502.html)具体怎么办?例如,根据某些参数,我想向不同的用户显示不同的登录页面。
    • 我会把它放在路由器中并为它编写路由测试。
    【解决方案2】:

    你应该使用:

    response.should render_template(:file => "#{Rails.root}/public/404.html")
    

    【讨论】:

    • 这不起作用:render_template(:file => "bogus file") 通过。
    • 为我工作 RSpec 3.2,Rails 4.2
    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多