3
2

More than 3 years have passed since last update.

【feature】Rspecで作成したテストデータに引数を渡す方法 let! ( ) {create( )}

Last updated at Posted at 2020-03-15

基本的なRspecの書き方についてはこちらに全て記載してあるので書きません。
https://qiita.com/jnchito/items/607f956263c38a5fec24

順序

・テストデータhoge_product、hoge_caetgoryを作成する
・hoge.categoryを持っているページにアクセスする
・カテゴリと紐づいた商品が表示されるテストを行う

コードに落とし込む

test_spec.rb
require 'rails_helper'

RSpec.feature "Categories", type: :feature do


let!(:hoge_caetgory) { create(:caetgory) } 
let!(:hoge_product) { create(:product ,caetgory: [caetgory]) } #caetgoryと言う引数(属性)を持ったproductを作成し、hoge_productというインスタンス変数に代入

  before do
    visit hoge_category_path(category)
  end

it カテゴリと紐づいた商品が表示される do
expect(page).to have_content hoge_product.category #caetgoryと言う引数(属性)を持ったhoge_productが表示されるテスト
end

let!(:hoge_product) { create(:product ,caetgory: [caetgory1]) }だったら、
categoryがcategory1であるproductを作成してくれます。

let!(:変数) { create(:データ ,引数) }のイメージです。

書き方のみの説明記事のため、コントローラについては割愛。

間違いがありましたらコメントください。

関連記事はこちら。
https://qiita.com/kojiro3/items/b0957813695ca61fa3aa

3
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
3
2