【RSpec】Feature specを調べた・書いた

環境

OS X Yosemite

Ruby 2.3.1

Rails 5.0.0

SQLite3

どう便利

書くことで、実装しなければいけないことが明確になります。
また、仕様からコードに落とし込むので、あいまいな点が早い段階でわかります。
さらに、後から参画するエンジニアにとって「あ、こんな機能あるんだ」という感じで、みんなハッピーです。

書いた

まず、specファイルを用意します。
spec/features/xxxxx_spec.rb
ファイルの末尾に`_spec`がついていれば良いです。

これからFeature specを書きますという宣言をします。

require 'rails_helper'

RSpec.feature '物件', :type => :feature do
end

次にどのようなユーザーの操作をシミュレートするか書きます。
scenarioはitに相当します。

require 'rails_helper'

RSpec.feature '物件', :type => :feature do
  # 追加
  scenario '編集ボタンを押したときに既存のデータが入力されている' do
  end
end

次にどのユーザーがどのURLにアクセスするか書きます

require 'rails_helper'

RSpec.feature '物件', :type => :feature do
  scenario '編集ボタンを押したときに既存のデータが入力されている' do
    # 追加
    visit edit_room_path
  end
end

`edit_room`は`rails routes`を実行するとわかります。

edit_room_pathはpath内に:idを要求してくるので、編集するオブジェクトを作成・取得します。

require 'rails_helper'

RSpec.feature '物件', :type => :feature do
  before do
    # ユーザーの作成
    Room.create(id: 1, name: 'ほげハイツ', price: 50000, address: '渋谷区神泉', building_age: 32, note: '備考')
  end
  # ユーザーの取得
  let(:room) { Room.find(1) }

  scenario '編集ボタンを押したときに既存のデータが入力されている' do
    # 引数にRoomオブジェクトを渡す
    visit edit_room_path room
  end
end

beforeの部分はbackgroundとも書けます。むしろそちらの方が良いです。
これでデータを編集するページにアクセスできるようになりました。
あとは期待する結果を書きます。

require 'rails_helper'

RSpec.feature '物件', :type => :feature do
  before do
    Room.create(id: 1, name: 'ほげハイツ', price: 50000, address: '渋谷区神泉', building_age: 32, note: '備考')
  end
  let(:room) { Room.find(1) }

  scenario '編集ボタンを押したときに既存のデータが入力されている' do
    visit edit_room_path room

    # 追加
    expect(page).to have_field '物件名', with: 'ほげハイツ'
    expect(page).to have_field '賃料', with: 50000
    expect(page).to have_field '住所', with: '渋谷区神泉'
    expect(page).to have_field '築年数', with: 32
    expect(page).to have_field '備考', with: '備考'
  end
end

let は given とも書けます。givenの方が良いです。

expect(page).to have_field '物件名', with: 'ほげハイツ'

はpage内に、「物件名」というラベルがあり、そのinputタグのvalue属性には'ほげハイツ'が入力されている
という意味になります。

次はFactoryGirlでテストに使用する共通のデータを書きます。