質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

3017閲覧

Rspecのテストを実行すると「raise WrongScopeError, "`#{name}` is not available from within an exam」というエラーになる

k499778

総合スコア599

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2021/02/22 06:20

編集2021/02/22 14:16

現在以下を参考にRails APIを作成し、Rspecでテストをしようとしています。
Railsで超簡単API
【Rails】APIテストの書き方

APIを作り終えて、Rspecの環境構築をし、テストを実装したので、bundle exec rspecでテスト実行すると以下のようなエラーが出ました。

F Failures: 1) PostAPI 全てのポストを取得する Failure/Error: raise WrongScopeError, "`#{name}` is not available from within an example (e.g. an " \ "`it` block) or from constructs that run in the scope of an " \ "example (e.g. `before`, `let`, etc). It is only available " \ "on an example group (e.g. a `describe` or `context` block)." `name` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block). (省略) Finished in 0.00662 seconds (files took 2.44 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/request/api/v1/posts_spec.rb:5 # PostAPI 全てのポストを取得する

これを解決するにはどうしたらいいでしょうか?
調べているのですが、なかなか解決できずにいます。
設定周りなのか、コードなのか、プロダクトコードが認識できていないのか、なにかライブラリが読み込めていないのか、、、いろんな予想を立てて調べています。

もしアドバイスいただける方がいらっしゃいましたらお願いいたします。

以下のようなフォルダ構成です
イメージ説明

以下のようなコードです。
↓posts_spec.rb

rb

1require 'rails_helper' 2# [Rails API Testing Best Practices] (https://matthewlehner.net/rails-api-testing-guidelines) 3 4describe 'PostAPI' do 5 it '全てのポストを取得する' do 6 post = create(:post, title: 'test-title') 7 8 get "/api/v1/posts/#{post.id}" 9 json = JSON.parse(response.body) 10 11 # リクエスト成功を表す200が返ってきたか確認する。 12 expect(response.status).to eq(200) 13 14 # 要求した特定のポストのみ取得した事を確認する 15 expect(json['data']['title']).to eq(post.title) 16 end 17end

PostmanでAPIのCRUDは実施確認済みです。(プロダクトコードは参考サイトと同様です。)

Gemfileは以下です。(「★追加」とコメントしているところがテストコード実装時に追加したものです。)

gemfile

1source 'https://rubygems.org' 2git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 4ruby '2.7.1' 5 6# Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' 7gem 'rails', '~> 6.1.2', '>= 6.1.2.1' 8# Use sqlite3 as the database for Active Record 9gem 'sqlite3', '~> 1.4' 10# Use Puma as the app server 11gem 'puma', '~> 5.0' 12# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 13# gem 'jbuilder', '~> 2.7' 14# Use Redis adapter to run Action Cable in production 15# gem 'redis', '~> 4.0' 16# Use Active Model has_secure_password 17# gem 'bcrypt', '~> 3.1.7' 18 19# Use Active Storage variant 20# gem 'image_processing', '~> 1.2' 21 22# Reduces boot times through caching; required in config/boot.rb 23gem 'bootsnap', '>= 1.4.4', require: false 24 25# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 26# gem 'rack-cors' 27 28group :development, :test do 29 # Call 'byebug' anywhere in the code to stop execution and get a debugger console 30 gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 31 gem 'factory_bot_rails' #★追加 32 gem 'rspec-rails', '~> 3.9.1' #★追加 33end 34 35group :development do 36 gem 'listen', '~> 3.3' 37 # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 38 gem 'spring' 39end 40 41# Windows does not include zoneinfo files, so bundle the tzinfo-data gem 42gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

追記

試したこと

・「rspec "#{name} is not available from within an example」で検索
結果、以下のサイトを確認しましたがピンとこず解決に至っていません。
https://stackoverflow.com/questions/45439673/rspec-mocking-name-not-available-from-within-an-example-group
https://qiita.com/opiyo_taku/items/6364adf27102d30f0e6d

・変数のスコープ絡みなのかな。といった観点でも調査。

・テストコードを中身がない状態や必ずtrueとなる状態にして実施→同じエラーが出る

rb

1require 'rails_helper' 2 3describe 'PostAPI' do 4 it '全てのポストを取得する' do 5 expect(1).to eq(1) #これを消しても同じエラー 6 end 7end

追記2
▼こちらに現在うまくRspecが起動できないプロジェクトを置きました。(blogプロジェクト)
https://github.com/k49977/railsAPI/tree/master/blog
「rails s」でサーバー起動し、
exec rspec spec/request/api/v1/posts_spec.rbでテストを実行すると現状のエラーになります。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

gouf

2021/02/22 10:44

GitHub などにソースコードは公開可能ですか?
solMackartony

2021/02/22 10:56 編集

コードなどはありますか?
k499778

2021/02/22 10:58

お返事頂きありがとうございます。帰りましたらGitHubに上げるように致します
gouf

2021/02/22 12:43

Ruby のバージョンが「2.7.1」に固定されていますが、これを下げることは可能ですか? たとえば バージョン「2.6.6」に変更した場合、何か変化は見られますか?
k499778

2021/02/22 13:55

やってみます
k499778

2021/02/22 14:07

Your Ruby version is 2.7.1, but your Gemfile specified 2.6.6 No examples found.
k499778

2021/02/22 14:08

上記のように出ました。 私の環境では「ruby -v」すると 「ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-darwin17]」となっているので、Gemfileもそれに合わせる必要がありそうです
k499778

2021/02/22 14:08

はじめてRspecを触るので、結構初歩的なミスかもしれません。。。
k499778

2021/02/22 14:14

rubyやrails自体もまだあまり慣れていない状態です。
guest

回答1

0

自己解決

一応解決できましたが、原因を整理できていないので行ったことを記載します。

①少しまだまだgemやbundle絡みの扱い方も怪しいのですが、
bundle updateやbundle cleanを行い、インストールされているgemをおそらくgemfileに書かれている通りに明示的に行いました。

②次に「undefined method "create"」「"undefined method 'get'"」と怒られたので、参考リンクより「FactoryBot.create」「, type: :request」とすることで解決できました。

↓spec/request/api/v1/posts_spec.rb

rb

1require 'rails_helper' 2 3describe 'PostAPI', type: :request do 4 it '全てのポストを取得する' do 5 post = FactoryBot.create(:post, title: 'test-title') 6 7 get "/api/v1/posts/#{post.id}" 8 json = JSON.parse(response.body) 9 10 # リクエスト成功を表す200が返ってきたか確認する。 11 expect(response.status).to eq(200) 12 13 # 要求した特定のポストのみ取得した事を確認する 14 expect(json['data']['title']).to eq(post.title) 15 end 16end

参考:
GETリクエストをするspecを実行して"undefined method get"と怒られた時は
Rspec - NoMethodError: undefined method `create' でエラーとなってしまいFactoryが適切に動かない

イメージ説明

もう少しヘルパーを使えばスッキリ書けそうな気もするし、元々参考にしていたサイトとコードが違うことも気になるので、もう少し数を打って、理解を深めたいと思います。

投稿2021/02/22 15:19

編集2021/02/23 15:44
k499778

総合スコア599

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問