Rails RSpec请求规范失败,因为意外的%2F添加到重定向响应

时间:2014-02-02 23:01:20

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

在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

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

1 个答案:

答案 0 :(得分:2)

删除旧答案没有帮助。这有效并经过测试:

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 # =>

Store
  books globbed route
    routes to public

Finished in 0.15973 seconds
1 example, 0 failures

Randomized with seed 15579