2017-03-17 38 views
1

我想創建一個RSpec測試,它檢測請求是否可以使控制器崩潰,通常是500錯誤。所以我想能夠區分之間:從如何測試請求不會返回500錯誤?

nil.invalid_method # raises NoMethodError 

params.require(:required_parameter) # raises ActionController::ParameterMissing 

在一個通用的方式的控制器。當我做了requestfeaturecontroller測試拋出一個異常:

describe "Post", type: :request do 
    it 'does not crash when no params given' do 
    post '/posts' # this line launches an exception 
    expect(page).to_not have_http_status(500) 
    end 
end 

看來,之前的RSpec(或者Rails我不知道)有不同的行爲,類似於我在尋找:

我該怎麼做?或者你會怎麼做?

謝謝你的時間。

+0

@max @spickermann我沒有正確解釋自己。我的觀點不是檢查引發了哪個異常。也許我的控制器正在以另一種方式處理這個問題,即:它會在html中返回一個錯誤消息。正因爲如此,我想要一個*通用的方式來檢測沒有「編碼錯誤」。 Rails使用異常來處理幾種正確的代碼,比如'ActionController :: ParameterMissing',因爲我不能使用'除了{...} .to_not raise_exception'。 –

回答

1

您可以使用一個控制器規範,不使一個500,但引發異常,而不是:

describe "PostController", type: :controller do 
    describe "POST index" do 
    it 'does not crash with valid params' do 
     expect { 
     post :index, { post: { title: 'foo' } } 
     }.to_not raise_exception 
    end 
    end 

    describe "POST index" do 
    it 'crashes without params' do 
     expect { 
     post :index 
     }.to raise_exception(ActionController::ParameterMissing) 
    end 
    end 
end 

還要注意expect後的大括號{ ... }

0

您可以測試控制器不使用raise_error匹配引發未捕獲的異常:如果該異常是通過使用rescue關鍵字或者Rails rescue_from你將考驗響應控制器救出

RSpec.describe "Things", type: :request do 
    describe "POST /things" do 
    it "does not raise an error" do 
     # we pass a block to expect 
     expect { post things_path }.to_not raise_error 
    end 
    end 
end 

代碼像往常一樣:

class ThingsController < ApplicationController 
    rescue_from ActionController::ParameterMissing do 
    head 500 
    end 

    def create 
    raise ActionController::ParameterMissing.new('foo') 
    end 
end 

RSpec.describe "Things", type: :request do 
    describe "POST /things" do 
    it "work even if the param is not provided" do 
     post things_path 
     expect(response).to successful 
    end 
    end 
end 

在這種情況下,它是有用得多測試響應是你希望它是什麼 - 不,它不是500