簡體   English   中英

Rspec rails:如何測試一次控制器操作是否正確地使用修改后的參數重定向到其自身?

[英]Rspec rails: How do I test if a controller action redirects correctly to itself with modified params once?

我有一個控制器操作(基於查詢參數)可能會通過一些修改后的參數重定向到自身

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

現在,我想做兩個這樣的測試:

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

但是它們不起作用。 有兩個問題:

  1. 在第一個測試中:在重定向后再次擊中相同動作之前,我似乎無法測試中間重定向。
  2. 在第二個測試中:我找不到一種方法來測試所有重定向都沒有發生。

我找到了這個相關的問題,但是並不能解決。 RSpec測試使用GET參數重定向到URL

對於第二個,我想您可以測試以下內容:

expect(response).to render_template(:your_template)

只需添加期望的模板,如果您不希望重定向,只需將模板添加到您希望保留的位置即可。

對於第一個,我不確定是否真的了解您的需求,但是我嘗試為您提供以下代碼:

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! 遵循單個重定向響應。 如果最后一個響應不是重定向,則會引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM