0
0

More than 1 year has passed since last update.

【RSpec】RSpecの実行中にletで定義したメソッドの中身を確認する際の注意点

Last updated at Posted at 2023-02-16

はじめに

Railsなどを中心に勉強中のエンジニア初心者が他の記事を参考にしたり、実際に実装してみたりして、アウトプットの一環としてまとめたものです。
間違っていることもあると思われるので、その際は指摘いただけると幸いです。

binding.pryでメソッドの中身が確認できない

下記のように記載して、テストデータが生成されていることを確認しようとした。

binding.pryで停止させることでメソッドの中身(productの中身)を確認できると思ったが、実際に中身を見てみると値を確認できず。。。

     5:   describe "GET /products" do
     6: 
     7:     let(:product) { create(:product) }
     8:     binding.pry                                       # こに記載する
     9: 
 => 10:     before do
    11:       # HTTPリクエストを実行
    12:       get product_path(product.id)
    13:     end
    14: 
    15:     it "商品詳細ページにアクセスできること" do

[1] pry(RSpec::ExampleGroups::Products::GETProducts)> product
RSpec::Core::ExampleGroup::WrongScopeError: `product` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc).
from /vendor/bundle/ruby/2.7.0/gems/rspec-core-3.10.1/lib/rspec/core/example_group.rb:741:in `method_missing'

letで定義したメソッドが使用できる範囲に注意

before doの中にbinding.pryを記載して停止されることで、メソッドの中身(productの中身)を確認することができた。

これは、letで定義したメソッドが使用できる範囲にが限られているため起こっている現象のようです。

本記事の初回の投稿では下記のように記載しておりましたが、誤りだったようですm(_ _)m

調べてみると、letでメソッドを定義したときは、定義した定数が初めて使われたときにcreateされるらしい(遅延評価)。
そのためletの下にbinding.pryを記載して停止しても、メソッドの値が確認できなかったと思われる(まだcreateされていなかった)。

    15:     before do
    16:       get product_path(product.id)
    17:       binding.pry
 => 18:     end
    19: 
    20:     it "商品詳細ページにアクセスできること" do
    21:       expect(response).to have_http_status(200)
    22:     end

[1] pry(#<RSpec::ExampleGroups::Products::GETProducts>)> product
=> #<Spree::Product:0x0000aaaacf444ee8
 id: 6,
 name: "Product #1 - 2763",
 description: "As seen on TV!",
 available_on: Sun, 06 Feb 2022 01:27:23.000000000 JST +09:00,
 deleted_at: nil,
 slug: "product-1-2763",
 meta_description: nil,
 meta_keywords: nil,
 tax_category_id: 6,
 shipping_category_id: 6,
 created_at: Mon, 06 Feb 2023 01:27:24.084964000 JST +09:00,
 updated_at: Mon, 06 Feb 2023 01:27:24.162491000 JST +09:00,
 promotionable: true,
 meta_title: nil,
 discontinue_on: nil

参考

最後に

いかがでしたでしょうか。
今回はRSpec実行時のメソッドの確認方法についてまとめてみました。
ここ違うよ!でしたり、こうした方がいいよ!などがあればコメントいただけると幸いです。

他にも下記のような記事を投稿しております。
興味がありましたら、ぜひご覧ください。

0
0
2

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
0
0