ApplicationControllerでヘルパーメソッドとして定義されたメソッドがあります。
helper_method :can_access_participant_contact_data?
ヘルパーファイルにあるヘルパーメソッドのテストを作成しようとしています。このヘルパーメソッドはを呼び出しますhelper_method :can_access_participant_contact_data?
# In participants_helper.rb
#
def redacted_contact_data participant, attribute_name
attribute = participant.try(:contact_data).try(attribute_name)
return attribute if can_access_participant_contact_data?(participant)
return nil if attribute.blank?
return attribute.gsub(/\S/i, '*') # Asterisked string
end
これまでのテストで行っているのは、redacted_contact_dataを呼び出すことだけです。
require 'test_helper'
class ParticipantsHelperTest < ActionView::TestCase
test "should return an asterisked string with spaces" do
redacted_contact_data(Participant.first, :name)
end
end
テストを実行すると、このメッセージが表示されます
undefined method `can_access_participant_contact_data?' for #<ParticipantsHelperTest:0x007fd6c7c6d608>
私は周りを見回してきましたが、この問題を回避する方法がわかりません。can_access_participant_contact_data?
どういうわけかモックする必要がありますか?または、メソッドをテストに含めることはできますか?
AFAIK(私の知る限り)では、スタブするか、コードに変更を加えることなくこれを修正することはできません。基本的に、ヘルパーファイルはそれ自体のモジュールであり、含まれる場所に関係なく処理する必要があるためです。たとえば、モデルファイル内にそのようなヘルパーファイルを含めることをお勧めします。ちなみに、モデルファイルにも名前can_access_participant_contact_data?
が付けられていApplicationController
ますが、で定義されているメソッドとは異なります。したがって、コンテキスト/ベースを指定せずにこれを単体テストすることはできません。 。
スタブ:
または手動で(おそらくより良い方法があります):
test "should return an asterisked string with spaces" do
ParticipantsHelper.class_eval do
define_method :can_access_participant_contact_data? do |arg|
true
end
end
redacted_contact_data(Participant.first, :name)
end
または、すべてのApplicationController
ヘルパーメソッドを別の/既存のヘルパーファイルに移動しますApplicationHelper
。たとえば、既存のヘルパーファイル内に移動します。その後、メソッド/ sieを使用しているテストしている他のヘルパーファイル内にそのヘルパーを含めます。
# helpers/application_helper.rb
module ApplicationHelper
def can_access_participant_contact_data?(participant)
# YOUR CODE
end
end
# helpers/participants_helper.rb
module ParticipantHelper
include ApplicationHelper
def redacted_contact_data participant, attribute_name
attribute = participant.try(:contact_data).try(attribute_name)
return attribute if can_access_participant_contact_data?(participant)
return nil if attribute.blank?
return attribute.gsub(/\S/i, '*') # Asterisked string
end
end
このアプローチを使用する場合、コントローラー内でヘルパーメソッドを呼び出す2つの方法:
helpers
コントローラ内でRailsメソッドを使用します。
class ParticipantsController
def show
helpers.can_access_participant_contact_data?(@participant)
end
end
または、ヘルパーを直接含めます(私は個人的に上記の他のアプローチを好みます)
class ApplicationController < ActionController::Base
include ApplicationHelper
end
class ParticipantsController < ApplicationController
def show
can_access_participant_contact_data?(@participant)
end
end
ビューファイルの場合、コードを更新する必要はありません。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加