LoginSignup
24
23

More than 3 years have passed since last update.

【Rails】RSpecで`visit`が`undefined method`と怒られたときの解決法

Posted at

はじめに

Rails+RSpec+Capybaraで書いたテストを実行しようとしたらタイトルのようなエラーが出た方に向けて解決法を残しておきます。

この記事が役に立つ方

  • タイトルのようなエラーで困っている方

この記事のメリット

  • エラー解決!

環境

  • macOS Catalina 10.15.1
  • zsh: 5.7.1
  • Ruby: 2.6.5
  • Rails: 5.2.3
  • RSpec: 3.9.0
  • Capybara: 3.29.0

エラー内容

NoMethodError:
       undefined method `visit' for #<RSpec::ExampleGroups::UsersIndex::IndexHtmlErb:...>

なぜかvisitが定義されていないことになっている。

原因

Capybaraが読み込まれていないことが原因です。

visitCapybara内で定義されているため読み込む必要があります。

解決法 その1

以下を追記します。

spec/spec_helper.rb
...

require 'capybara/rspec' # 追記

RSpec.configure do |config|

...

解決法 その2(1で解決しなかった場合)

もういっちょ追記します。

spec/spec_helper.rb
...

require 'capybara/rspec'

RSpec.configure do |config|
  config.include Capybara::DSL # 追記

...

なぜ解決したのか?

公式のREADMEに答えが書いています。(※以下はバージョン3.29対応版)
capybara/README.md at 3.29_stable · teamcapybara/capybara · GitHub

Load RSpec 3.5+ support by adding the following line (typically to your spec_helper.rb file):

RSpec3.5以上を使っているなら、spec_helper.rbに以下を追記してねと書いてあります。

require 'capybara/rspec'

これでCapybaraが読み込まれることになります。
ここまでが解決策1の範囲です。

ただ、これで解決しない方はREADMEの次の文章に答えが書いてあります。

If you are using Rails, put your Capybara specs in spec/features or spec/system (only works if you have it configured in RSpec) and if you have your Capybara specs in a different directory, then tag the example groups with type: :feature or type: :system depending on which type of test you're writing.

書いたテストが以下ディレクトリにあるか、
spec/features
spec/system

タグが以下でないとCapybaraが読み込まれません。
type: :feature
type: :system

そのため、それ以外のパターンに該当してしまう場合は
解決法 その2
で追記したように強制的にCapybara::DSLを読み込んでしまうことで解決出来ます。

おわりに

自分は結構ここでハマってしまったので、同じような方の役に立てればと思います。

日本語の記事で楽をせず、困ったら公式を見ないといけませんね:sweat_smile:

参考にさせて頂いたサイト(いつもありがとうございます)

capybara/README.md at 3.29_stable · teamcapybara/capybara · GitHub

24
23
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
24
23