[英]Rspec rails: How do I test if a controller action redirects correctly to itself with modified params once?
I have a controller action which (based on the query params) might redirect to itself with some modified params 我有一个控制器操作(基于查询参数)可能会通过一些修改后的参数重定向到自身
class SearchController < ApplicationController
def search
if params[:deprecated_param].present?
params[:new_param] = params.delete(:deprecated_param)
redirect_to search_path(params), status: :moved_permanently and return
end
end
end
Now I would like to make two tests something like this: 现在,我想做两个这样的测试:
require 'spec_helper'
describe SearchController, type: :controller do
describe 'GET #search' do
render_views
context 'a deprecated param is used' do
it 'should do a redirect' do
get :search, deprecated_param: 'yes'
expect(response).to redirect_to("http://mydomain.test/search?new_param=yes") # .once ?
# expect(final response after redirect).to have_http_status(200)
end
end
context 'when no deprecated param is used' do
it 'should not do any redirects' do
get :search, new_param: 'yes'
expect(response).not_to #... redirect_anywhere?
expect(response).to have_http_status(200)
end
end
end
end
However they don't work. 但是它们不起作用。 There are two problems: 有两个问题:
I found this related question, but it does not solve it. 我找到了这个相关的问题,但是并不能解决。 RSpec testing redirect to URL with GET params RSpec测试使用GET参数重定向到URL
For the second one I guess you can test the following things: 对于第二个,我想您可以测试以下内容:
expect(response).to render_template(:your_template)
Just add the expected template, if you want no redirection just add the template where you expect to stay. 只需添加期望的模板,如果您不希望重定向,只需将模板添加到您希望保留的位置即可。
For the first one, I am not sure to really understand what you need but I try to advise you the following code: 对于第一个,我不确定是否真的了解您的需求,但是我尝试为您提供以下代码:
describe SearchController, type: :request do
# ...
it 'should do a redirect' do
get "/search", deprecated_param: 'yes'
expect(response).to redirect_to("http://mydomain.test/search?new_param=yes")
follow_redirect!
expect(response).to have_http_status(200)
expect(response).to render_template(:your_template) #just to be sur you are on the expected page
end
follow_redirect!
follow a single redirect response. 遵循单个重定向响应。 If the last response was not a redirect, an exception will be raised. 如果最后一个响应不是重定向,则会引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.