じぶんメモ

プログラミングのメモ、日常のメモとか。

rspec内でCSFR対策を有効にする

railsでpost送信を行う際に、画面を経由しないリクエストには422が返却される。 これはrailsCSRF対策である、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