2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【FactoryBot + RSpec】パスにクエリを渡すのに苦労した話

Last updated at Posted at 2019-09-26

Webエンジニア1年生がRSpecで
「パスにクエリを渡したい!
でもFactoryBotで作成したテストデータの中身をどうやってパスに渡すの?」
と苦労したけど、実がとても簡単だった話

開発環境

  • Ruby 2.5.5
  • Rails 5.2.3
  • RSpec 3.8

実現したいこと

FactoryBot + RSpecでページ遷移の際にパスにクエリを渡し、それが正しいことをexpectしたい
(http://○○.com/reviews/new ?item_id=20)←クエリ

先に結論

assignsメソッドを使う!

とある商品のレビューをするサイトを作っているとする
商品検索画面から商品を選択後、その商品のレビュー投稿ページへ商品IDをパスに持たせて遷移する場合

assets/controllers/items_controller.rb
class ItemsController < ApplicationController
  def search
    @item = #(フォームから送られてきた商品情報)

    # 〜中略〜

    redirect_to new_review_path(item_id: @item.id)
    # 商品idを渡してレビューページへ遷移する
    # /reviews/new?item_id=20
  end
end

これが正しく遷移することをRSpecでテストします。

spec/factories/item.rb
FactoryBot.define do
  factory :item, class: Item do
    id { 1 }
    name { 'ボールペン' }
    # 〜中略〜
  end
end
spec/controllers/items_controller_spec.rb
require 'rails_helper'

RSpec.describe ItemsController, type: :controller do
  describe 'POST #search' do
    before do
      post :search, params: { item: attributes_for(:item) }
      # attributes_for(:item) = { id: 1, name: 'ボールペン', ・・・〜中略〜・・・ }
    end

    it '選択された商品のレビューページへ遷移する' do
      expect(response).to redirect_to new_review_path(item_id: assigns(:item).id)
    end
  end
end

assignsメソッドとは

コントローラのインスタンス変数に代入されたオブジェクトは、コントローラの assigns メソッド経由で参照できます。
参照する場合には、インスタンス変数名から “@” を除いたものをシンボルまたは文字列にしたものをキーとして指定します。

@itemassigns(:item)に書き換えることで使えるようになるんですね!

redirect_to new_review_path(item_id: @item.id)
↓
redirect_to new_review_path(item_id: assigns(:item).id)

参考記事

・ スはスペックのス 【第 2 回】 RSpec on Rails (コントローラとビュー編)
  https://magazine.rubyist.net/articles/0023/0023-Rspec.html#assigns-%E3%81%AB%E3%82%88%E3%82%8B%E5%8F%82%E7%85%A7

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?