如何獲得此錯誤的測驗通過?
Rspec 控制器和結果
context 'invalid confirmation_token' do
subject do
post signup_step5_path,
params: {
user: {
password: 'hoge',
password_confirmation: 'hoge',
confirmation_token: 'wrong_token'
}
}
end
let(:user) { User.find_by(confirmation_token: 'testtesttest') }
it 'does not update user attributes and never create an end_point record' do
expect { subject }.raise_error(ActiveRecord::RecordNotFound)
expected ActiveRecord::RecordNotFound but nothing was raised
控制器方法我拯救了 ActiveRecord::RecordNotFound 并在私有方法中呈現 404 頁面。
class Users::SignupController < ApplicationController
layout 'devise'
rescue_from ActiveRecord::RecordNotFound, with: :render404
def step5
@user = User.find_by(confirmation_token: step5_params[:confirmation_token])
raise ActiveRecord::RecordNotFound unless @user
.....
end
private
def render404(error = nil)
logger.info "Rendering 404 with exception: #{error.message}" if error
render file: Rails.root.join('public/404.ja.html'), status: :not_found
end
end
uj5u.com熱心網友回復:
首先,解釋例外匹配器實際上只會匹配未捕獲的例外可能是一個好主意。那是因為它基本上只是一個救援陳述句并在它使呼叫堆疊冒泡時拯救例外,并且它旨在測驗一段代碼是否引發了由消費者來捕獲的例外 - 這是測驗行為的一個示例。
另一方面,測驗代碼引發和拯救例外是測驗它如何作業。
def foo
raise SomeKindOfError
end
def bar
begin
raise SomeKindOfError
rescue SomeKindOfError
puts "RSpec will never catch me!"
end
end
describe "#foo" do
it "raises an exception" do
expect { foo }.to raise_exception(SomeKindOfError)
end
end
describe "#bar" do
it "rescues the exception" do
expect { bar }.to_not raise_exception(SomeKindOfError)
end
end
當您使用rescue_from它基本上只是語法糖來使用 around_action 回呼來挽救給定的例外時:
class ApplicationController
around_action :handle_errors
private
def handle_errors
begin
yield
rescue SomeKindOfError
do_something
end
end
end
盡管 RSpec 曾經有bypass_rescue過控制器規范,但 Rails 和 RSpec 團隊都非常不鼓勵使用控制器規范,而且您實際上只是在測驗實作而不是行為。
相反,您應該測驗實際控制器做什么而不是它如何做。
context 'invalid confirmation_token' do
# explicit use of subject is a code smell
before do
post signup_step5_path,
params: {
user: {
password: 'hoge',
password_confirmation: 'hoge',
confirmation_token: 'wrong_token'
}
}
end
let(:user) { User.find_by(confirmation_token: 'testtesttest') }
it 'does not update the users password' do
expect(user.valid_password?('hoge')).to be_falsy
end
it 'returns a 404 - NOT FOUND' do
expect(response).to have_http_status(:not_found)
end
# using Capybara in a feature spec is a better way to do this.
it 'renders something' do
expect(response.body).to match("Oh Noes!")
end
end
uj5u.com熱心網友回復:
假設它是一個請求規范,請求將回傳 HTTP 404,您可以為此設定一個期望:
is_expected.to be_not_found
邊注:
@user = User.find_by(confirmation_token: step5_params[:confirmation_token])
raise ActiveRecord::RecordNotFound unless @user
可以簡化為:
@user = User.find_by!(confirmation_token: step5_params[:confirmation_token])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375555.html
上一篇:RubyonRails未定義“John”的方法`delete_at':字串
下一篇:Ransackgem找不到結果
