自学-堅牢なシステム設計(Rails)②
前回記事:自学-堅牢なシステム設計(Rails)の続き
■
■
example "suspendflgをセットする" do
params_hash.merge!(suspended: true)
patch admin_staff_members_url(staff_member),
params_hash: {staff_member: params_hash}
staff_member.reload
expect(staff_member).to be_suspended
end
example "hashed_passwordの値は下記かえ不可" do
params_hash.delete(:password)
params_hash.merge!(hashed_password: "x")
expect {
patch admin_staff_members_url(staff_member),
params: {staff_member: params_hash}
}.not_to change {staff_member.hashed_password.to_s}
end
- params_hashのmergeメソッドで一部の値を入れ替える
- patchメソッドは部分置換で、paramsの二つのパラメータを送る
- StaffMemberオブジェクトをリロードして、各属性値をDBから再取得する
- be_suspendedはマッチャーとして定義されていない。
- Rspecは内部挙動として、be_xxxがあれば、prefixを消して、suffixに?を付けたメソッドを呼び出す
- なので、staff_memberのsuspended?を呼んでいる
- hashed_passwordが変更できないことの試験
- expect {x}.not_to change {Y}は、属性値が変更しないことを検証するテンプレ
- hashed_password.to_sのto_sの理由は、BCrypt::Passwordオブジェクトは生パスワードを比較するが、changeマッチャーは値の変化を調べるので、整合性が取れないから
■
400 Bad Requestを使う場面
- Paramaterが間違っている状態なので、「400 Bad Request」を使う
- ErrorHandlerモジュールに例外処理メソッドrescue400を作成する
- それをクラスメソッドrescue_fromで例外ハンドラとして登録する
module ErrorHandler
extend ActiveSupport::Concern
included do
rescue_from StandardError, with: :rescue500
rescue_from ApplicationController::Forbidden, with: :rescue403
rescue_from ApplicationController::IpAddressRejected, with: :rescue403
rescue_from ActiveRecord::RecordNotFound, with: :rescue404
rescue_from ActionController::ParameterMissing, with: :rescue400
end
private def rescue400(e)
render "error/bad_request", status: 400
end
テンプレートも作る
bin/rails g controller staff/accounts
スタッフ自身のアクション定義
一般ユーザーによるアカウント管理機能400 Bad Request
不正な要求です
bin/rails g controller staff/accounts
スタッフ自身のアクション定義
class Staff::AccountsController < Staff::Base
def show
@staff_member = current_staff_member
end
def edit
@staff_member = current_staff_member
end
def update
@staff_member = current_staff_member
@staff_member.assign_attributes(staff_member_params)
if @staff_member.save
flash.notice = "更新"
redirect_to :staff_account
else
render action: "edit"
end
end
private def staff_member_params
params.require(:staff_member_params).permit(
:email, :family_name, :given_name,
:family_name_kana, :given_name_kana
)
end
end
----