Rails/webpacker: share dynamically compiled assets between the dev and test environments

This is a super quick post. One of the most annoying things about system tests (at least for me), is that by default the test environment cannot benefit from the dynamic and fast compilation of assets whenever a change is made, by using webpack’s dev server. The dev server works well with the development environment, but not with tests. This means that each time you make a change to any assets, system or integration tests will start slowly because the assets must be compiled first.

I couldn’t find a solution for this involving the webpack dev server, and I found this comment where it is said that it basically cannot work with tests.

I’m happy though because I found an alternative/workaround which works really well! Instead of running

bin/webpack-dev-server

I run

bin/webpack --watch --colors

This makes sure that the assets are compiled dynamically when they change, and written to the filesystem (as opposed to in memory like with the dev server) in the directory public/paths. By default, the test environment in in config/webpacker.yml is configured so that the assets are compiled from scratch each time, and the directory were the compiled assets are written to is public/packs-test.

So, what I did is change config/webpacker.yml as follows:

test:
  <<: *default
  compile: false
  public_output_path: packs

This way we disable the full compilation at startup and we tell the test environment to load the packs from the same directory used for the development environment.

Voila’, dev and test environment now share dynamically compiled assets. I’m working on a relatively new app and this already makes quite a difference because it saves precious seconds for a faster feedback when changing assets and tests. I can imagine the difference can be more significant with larger apps.

Hope it’s useful!