【问题标题】:Rails RSpec request spec fails because unexpected %2F added to redirect responseRails RSpec 请求规范失败,因为向重定向响应添加了意外的 %2F
【发布时间】:2014-02-02 23:01:20
【问题描述】:

在 config/routes.rb 中:

get 'books(/*anything)' => redirect( "/public/%{anything}" ), :format => false

在 spec/requests/store_request_spec.rb 中:

get '/books/aoeu/snth'
expect(response).to redirect_to( '/public/aoeu/snth' )

这失败了:

Failure/Error: expect(response).to redirect_to( '/public/aoeu/snth' )
   Expected response to be a redirect to <http://www.example.com/public/aoeu/snth> but was a redirect to <http://www.example.com/public/aoeu%2Fsnth>.
Expected "http://www.example.com/public/aoeu/snth" to be === "http://www.example.com/public/aoeu%2Fsnth".
 # ./spec/requests/store_request_spec.rb:14:in `block (3 levels) in <top (required)>'

为什么 %2F 被插入到重定向响应中,我该如何防止它?

编辑:

如果我使用:

get 'books(/*anything)' => redirect( CGI::unescape("/public/%{anything}") ), :format => false

要创建一个未转义的字符串,我仍然会遇到同样的错误。

【问题讨论】:

  • %2F 是正斜杠 (/) 的 URL 编码。您是否尝试在传递给重定向的字符串上调用 html_safe
  • 我确实尝试过 html_safe 但没有帮助。这不是 HTML 编码类型问题。
  • 呃。我在逃跑方面遇到了很多问题 - 我将查看一些旧代码,看看我是否遇到了这个确切的问题。

标签: ruby-on-rails rspec-rails rails-routing


【解决方案1】:

删除了旧答案,因为它没有帮助。这有效并经过测试:

routes.rb:

get 'books/*anything', to: redirect { |params, request|
  path = CGI.unescape(params[:anything])
  "http://#{request.host_with_port}/public/#{path}"
}

spec/requests/store_request_spec.rb:

describe "books globbed route" do
  before { get('/books/abcd/efgh') }
  it "routes to public" do

    expect(response).to redirect_to('/public/abcd/efgh')

  end
end

运行bundle exec rspec spec/requests/store_request_spec.rb # =&gt;

Store
  books globbed route
    routes to public

Finished in 0.15973 seconds
1 example, 0 failures

Randomized with seed 15579

【讨论】:

  • 您的解决方案在早期测试中导致错误,该测试在任何内容中都只有一个片段。 URI::InvalidURIError:错误的 URI(不是 URI?):/public/%{CGI.escape(anything)}。我想我需要一些方法来防止输入被编码。我该怎么做?
  • 我自己发现这些东西可能很棘手 - 也有一个 CGI.unescape 方法 - 你可以在管道上进一步使用它
  • 谢谢。我试过了(见帖子编辑),我遇到了同样的问题。
  • 工作!我已经编辑了我的答案以包含工作代码。我也运行了 rspec 测试,它是绿色的
  • 太棒了!谢谢!看到您的回答后,我找到了相关文档:# api.rubyonrails.org/classes/ActionDispatch/Routing/…
猜你喜欢
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
相关资源
最近更新 更多