RailsApp Rails RSpec 2018年 11月 27日
describe 'GET #new' do
subject { -> { get new_kurasu_path } }
it_behaves_like :response_status_check, 200
end
def new
@kurasu = current_teacher.kurasus.build(name: 'クラス名', obsolete: false)
end
- content_for :title do
- @title = "#{t '.title'}: #{current_teacher.name}"
= render partial: 'form', locals: {kurasu: @kurasu}
- is_edit = controller.action_name == 'edit'
= form_with model: kurasu, local: true do |f|
%table
%tr
%th= f.label :name
%td= f.text_field :name, autofocus: true
- if is_edit
%tr
%th= f.label :obsolete
%td= f.check_box :obsolete, {checked: kurasu.obsolete}, 'true', 'false'
%tr
%td{colspan: 2}
- unless is_edit
= f.hidden_field :obsolete
= f.hidden_field :teacher_id
= f.submit
describe 'POST #create' do
before { @attrs = object.attributes; object.destroy }
subject { -> { post kurasus_path(edit_mode: true), params: {kurasu: @attrs}} }
context '正しいパラメータに対して' do
it_behaves_like :response_status_check, 302
it_behaves_like :increment_object_by_create, Kurasu
it_behaves_like :flash_notice_message, 'クラスを登録しました.'
it_behaves_like :redirect_to
end
describe '不正なパラメータに対して' do
before { @attrs['name'] = nil }
it_behaves_like :response_status_check, 200
it_behaves_like :not_increment_object_by_create, Kurasu
it_behaves_like :flash_alert_message, 'クラスが登録できません.'
end
end
def create
@kurasu = Kurasu.new(kurasu_params)
if @kurasu.save
redirect_to kurasus_path(edit_mode: true), notice: notice_message(Kurasu)
else
flash.now[:alert] = alert_message(Kurasu)
render action: :new
end
end
def kurasu_params
params.require(:kurasu).permit(:teacher_id, :name, :obsolete)
end
private :kurasu_params
def notice_message(klass)
I18n.t "flash.#{action_name}.notice", {obj: klass.model_name.human}
end
def alert_message(klass)
I18n.t "flash.#{action_name}.alert", {obj: klass.model_name.human}
end
ja:
flash:
create:
notice: "%{obj}を登録しました."
alert: "%{obj}が登録できません."
update:
notice: "%{obj}を更新しました."
alert: "%{obj}が更新できません."
edit:
alert: "%{obj}を編集する権限がありません."
destroy:
notice: "%{obj}を削除しました."
alert: "%{obj}を削除する権限がありません."
show:
alert: "%{obj}を表示する権限がありません."
GET #new
behaves like response_status_check
response should be 200
POST #create
正しいパラメータに対して
behaves like response_status_check
response should be 302
behaves like increment_object_by_create
should change `Kurasu.count` by 1
behaves like redirect_to
should redirect to "/kurasus?edit_mode=true"
behaves like flash_notice_message
should eq "クラスを登録しました."
不正なパラメータに対して
behaves like response_status_check
response should be 200
behaves like not_increment_object_by_create
should not change `Kurasu.count`
behaves like flash_alert_message
should eq "クラスが登録できません."
長くなったので今日はここまで