2016-11-30 65 views
1

我有一個測試控制器動作的rspec測試。測試控制器在RSpec中的重定向

class SalesController < ApplicationController 
    def create 
    # This redirect sends the user to SalesController#go_to_home 
    redirect_to '/go_to_home' 
    end 

    def go_to_home 
    redirect_to '/' 
    end 
end 

我控制器測試看起來像

RSpec.describe SalesController, type: :controller do 
    include PathsHelper 

    describe 'POST create' do 
    post :create 

    expect(response).to redirect_to '/' 
    end 
end 

然而,當我運行測試它告訴我,:

Expected response to be a redirect to <http://test.host/> but was a redirect to <http://test.host/go_to_home>. 
    Expected "http://test.host/" to be === "http://test.host/go_to_home". 

/go_to_home將發送用戶SalesController#go_to_home。我如何測試該響應最終將導致主頁的網址爲http://test.host/

回答

1

控制器測試是有效的單元測試 - 您正在測試調用單個動作的效果以及該動作的預期行爲。

create動作確實與302狀態碼返回一個響應返回,並且包括在所述報頭中的Location指示新的URI,它在呼叫建立將Location: http://localhost/go_to_home

的情況下這是儘可能的控制器測試進行。它模擬了從瀏覽器到創建操作的調用並接收到初始重定向。

在現實世界中,瀏覽器當然會導航到給定的位置,然後打到go_to_home動作,但這超出了控制器測試的範圍......這是集成測試領域。

所以,要麼,

  1. 創建一個集成測試最初叫create動作,請您在「/」結束的重定向和測試。
  2. 改變控制器測試expect(response).to redirect_to '/go_to_home'
  3. 更改create行動直接重定向到「/」
2

爲什麼期望在規格中重定向到'/'? 從你粘貼你會被重定向到/ go_to_home「打黑創建行動

嘗試改變規格後的控制器代碼:

expect(response).to redirect_to '/go_to_home' 

編輯:

這是一個真正的示例或代碼只是爲了分享您想要實現的目標? 我不認爲rspec在去'/ go_to_home'後會跟着重定向,我覺得很好。

如果您正在測試創建操作,則可以將測試重定向到「/ go_to_home」,因爲這是操作的過程。 然後,您可以爲其他操作go_to_home做另一個測試,並期望重定向到根。

你是否正在從別處調用行爲'go_to_home'?

+0

我會澄清我的問題。 '/ go_to_home'會將用戶發送到SalesController#go_to_home。 – jason328

+0

不,我只從SalesController#create調用go_to_home。瞭解我已經簡化了這個例子,所以有很多邏輯缺失。 – jason328