rspec内でCSFR対策を有効にする
railsでpost送信を行う際に、画面を経由しないリクエストには422が返却される。
これはrailsのCSRF対策である、ActionController::Base.allow_forgery_protection
がtrueになり、ApplicationControllerの protect_from_forgery with: :exception
で、CSRFチェックでNGだった場合に例外を発生させる設定になっているため。
rspecで使われるtest環境ではallow_forgery_protectionがfalseになっているが、rspec時にCSFR対策を有効にするには
ActionController::Base.allow_forgery_protection = true
とする。
describe 'createの確認' do let(:params) { FactoryGirl.build(:post).attributes } before { ActionController::Base.allow_forgery_protection = true } after { ActionController::Base.allow_forgery_protection = false } it 'レスポンスに422が返されること', autodoc: true do post '/api/v1/posts/create', params expect(response.status).to eq(422) expect(response).not_to be_success end end