LoginSignup
4
2

More than 3 years have passed since last update.

Rails EngineのRootからRSpecを実行すると、Webpackerのエラーが出たので対応する

Last updated at Posted at 2019-10-04

状況

アプリケーションが複数のUIで構成されているので、以下のような対応をしていた。分離することで、Webpackのバージョンから何やら分けることができる。

Webpackerのインスタンスをクラスメソッドで定義して、別のところから呼び出せるようにする。

module Convenience
  ROOT_PATH = Pathname.new(File.join(__dir__, ".."))

  class << self
    def webpacker
      @webpacker ||= ::Webpacker::Instance.new(
        root_path: ROOT_PATH,
        config_path: ROOT_PATH.join("config/webpacker.yml")
      )
    end
  end
end

ヘルパーに以下を記載し、先程のインスタンスを呼ぶようにすれば、stylesheet_pack_tagやjavascript_pack_tagが呼びだせる。

module Convenience
  module ApplicationHelper
    include ::Webpacker::Helper

    def current_webpacker_instance
      Convenience.webpacker
    end
  end
end

ちなみにこのメソッドは、カレントWebpackerインスタンスを返すので、先程のConvenienceの例だと、ConvenienceのWebpackerインスタンスを返すようにOverrideしてあるようだ。

module Webpacker::Helper
  # Returns current Webpacker instance.
  # Could be overridden to use multiple Webpacker
  # configurations within the same app (e.g. with engines)
  def current_webpacker_instance
    Webpacker.instance
  end

RSpecでエラー

ただ、EngineRootからrspecを実行するとエラーになるので、test環境だけ分岐する必要がある。もしかしたらもっといい方法があるのかもしれないが、一旦EngineRootから直でrspecを呼び出すという要件に合わせるためにコードを追記した。

module Convenience
  module ApplicationHelper
    include ::Webpacker::Helper

    unless Rails.env.test?
      def current_webpacker_instance
        Convenience.webpacker
      end
    end
  end
end

なお、コードは https://github.com/rails/webpacker/blob/master/docs/engines.md#using-in-rails-engines こちらからコピペしたものだと予想できる。

4
2
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
4
2