【问题标题】:How do I test that a 301 redirect takes place with rspec?如何使用 rspec 测试是否发生 301 重定向?
【发布时间】:2011-04-27 01:25:27
【问题描述】:

我需要测试两件事:

  1. 某些旧路径正确重定向到某些新路径
  2. 重定向是 301,而不是 302。

我正在使用 Capybara 进行验收测试,但这无法处理 #2。我可以测试重定向是否发生,但它是静默发生的,所以我看不出它是 301。

控制器测试无法处理 #1。 rspec 为控制器测试提供的“get”、“post”等动词只允许你传入一个动作,而不是特定的路径,并且重定向是基于路径在单个动作中实现的,如下所示:

# controller
class ExampleController
  def redirect301
    redirect_to case request.path
    when '/old_a'
      '/new_a'
    when '/old_b'
      '/new_b'
    end, :status => 301
  end
end

# routes.rb
['old_a', 'old_b'].each do |p| 
  map.connect p, :controller => :example, :action => :redirect301
end

那么,我该怎么办?

【问题讨论】:

    标签: ruby-on-rails testing rspec


    【解决方案1】:

    试试这个:

    it "should redirect with 301" do
      get :action
      response.code.should == 301
    end
    

    【讨论】:

    • OK,测试动作是否存在并返回 301,但如果“old_a”被重定向到“new_b”,这仍然会通过,反之亦然。
    • 那么您需要检查重定向状态或重定向 url 吗?
    • 然后检查 response.location 值。它将具有域+路径。或 response.fullpath 仅用于路径部分(仅限 rails 3)。
    • 正确的响应会因 url 的内容而异(参见我的代码 sn-p),如果“get”只允许我定义一个操作,我无法更改它。
    【解决方案2】:

    要测试响应状态,请执行此操作 - expect(response.status).to eq(301) 并测试响应网址这样做 - expect(response.location).to eq(my_path)

    所以它应该看起来像这样:

    it "should redirect with a 301 status code to my_path" do
      get :action
      expect(response.status).to eq(301)
      expect(response.location).to eq(my_path)
    end
    

    【讨论】:

      【解决方案3】:

      使用 rspec-rails 2.12.0 和现代 expect 语法,这是正确的格式:

        it "should redirect with a 301 status code to /whatever_path" do
          get :some_action
          expect(response).to redirect_to '/whatever_path' # or a path helper
          expect(response.code).to eq '301'
        end
      

      注意字符串 301 - 当我使用整数运行此规范时,它失败了,将 301 与 Ruby 中不相等的“301”进行比较。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-12
        • 2011-11-17
        • 2012-02-12
        • 1970-01-01
        • 2012-11-26
        • 2012-06-25
        • 2023-03-25
        • 2011-10-18
        相关资源
        最近更新 更多