[RSpec 3] Rails の Ajax 処理を RSpec でテストする

前回のシンプルな例へのテストコードを書いてみる。

[markdown]
> * [Rails における Ajax 処理のシンプルなチュートリアル | deadwood](https://www.d-wood.com/blog/2017/04/25_8912.html)

こちらを参考にさせて頂きました。

> * [RSpecでAjaxリクエストに対しRequest Spec(結合テスト)を行う | EasyRamble](http://easyramble.com/ajax-request-test-with-rspec.html)

## RSpec

FactoryGirl でオブジェクトを生成できるように準備する。

> * [Factory Girl Railsのチートシート – Rails Webook](http://ruby-rails.hatenadiary.com/entry/20150102/1420174315)

“`ruby:spec/factories/items.rb
FactoryGirl.define do
factory :item do
name ‘foo’
title ‘bar’
description ‘buzz’
:
“`

`xhr` method でリクエストを投げる。
引数は `request_method, path, parameters, headers_or_env`

> * [ActionDispatch::Integration::RequestHelpers](http://api.rubyonrails.org/v4.2.7.1/classes/ActionDispatch/Integration/RequestHelpers.html#method-i-xhr)

“`ruby:spec/requests/items_spec.rb
# frozen_string_literal: true
require ‘rails_helper’
RSpec.describe ‘Items’, type: :request do
describe ‘Search’ do
describe ‘GET /items/search’ do
it ‘works!’ do
get search_items_path
expect(response).to have_http_status(200)
end
end
describe ‘Search items with Ajax’ do
before do
create_list(:item, 9)
create(:item, name: ‘キーワードを含む名前’, title: ‘タイトル’)
end
it ‘returns 10 items’ do
xhr :post, result_items_path, keyword: ‘buzz’
expect(assigns[:results].size).to eq(10)
end
it ‘returns no item’ do
xhr :post, result_items_path, keyword: ‘keyword’
expect(response.body).to match(‘No items found.’)
end
it ‘returns a item’ do
xhr :post, result_items_path, keyword: ‘キーワード’
expect(response.body).to match(‘タイトル’)
end
end
end
end
“`

こちらで勉強中。

> * [Everyday Rails… by Aaron Sumner et al. [Leanpub PDF/iPad/Kindle]](https://leanpub.com/everydayrailsrspec-jp)

## 補遺

* [RSpec の ControllerSpec でパラメータとともに post 送信するテスト | EasyRamble](http://easyramble.com/rspec-controller-spec-post.html)
[/markdown]