LoginSignup
22
11

More than 5 years have passed since last update.

RSpecでテストを書いていたら別ファイルのhelperメソッドの呼び出しが undefined method になって困った時

Posted at

テスト対象のファイル以外に自分で記述したhelper methodが呼べない!と怒られた時の解決策。

  • sample_helper.rb で定義したメソッドをテストしたい
  • テスト対象のメソッドが別のファイル(util_helper.rb)で定義したメソッドを使ってたりすると・・・

コード

app/helpers/util_helper.rb
module UtilHelper
  def my_useful_method
    'very useful'
  end
end
app/helpers/sample_helper.rb
module SampleHelper
  def my_sample_method
    "#{my_useful_method} sample_method"
  end
end

スペック

helpers/sample_helper_spec.rb
require 'rails_helper'

RSpec.describe SampleHelper do
  describe "my_sample_method" do
    it { expect(my_sample_method).to eq 'very useful sample_method' }
  end
end

実行すると・・・

こんな感じのエラーになってしまう

NameError: undefined local variable or method `my_useful_method' for #<RSpec::ExampleGroups::SampleHelper::MySampleMethod:0x007ff1f93e06a0>

ぐぬ・・

解決策

使いたいメソッドが定義されている helper module をインクルードしてあげれば良い。

helpers/sample_helper_spec.rb
require 'rails_helper'

RSpec.describe SampleHelper do
  describe "my_sample_method" do
    include UtilHelper ## ここ
    it { expect(my_sample_method).to eq 'very useful sample_method' }
  end
end

解決策引用元

How to call an app helper method from an RSpec test in Rails? - Stack Overflow


普通にviewで使ってる分には、どこのファイルに書いてあっても呼べちゃう helper method だけに、うっかり別々のファイルに分かれてしまっていると、specの時だけなぜかメソッドないとか怒られて悲しいことになる・・

22
11
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
22
11