Skip to content

Instantly share code, notes, and snippets.

@stevehanson
Last active April 16, 2018 11:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevehanson/d51aa2e70dc0c9dac07c0fb6317644b4 to your computer and use it in GitHub Desktop.
Save stevehanson/d51aa2e70dc0c9dac07c0fb6317644b4 to your computer and use it in GitHub Desktop.
Webpacker - When running tests, compile only if necessary
# spec/rails_helper.rb
require_relative 'support/webpack_test_helper.rb'
# ...
config.before(:suite) do
# Compile webpack if necessary.
# Only runs if checksum of JS files has changed
WebpackTestHelper.compile_webpack_assets
end
# spec/support/webpack_test_helper.rb
# Discussion Reference: https://github.com/rails/webpacker/pull/360
# Source modified from this closed PR: https://github.com/rails/webpacker/pull/341
class WebpackTestHelper
class << self
def compile_webpack_assets
unless checksum_matches?
write_checksum
Webpacker.compile
end
end
private
def checksum
files = Dir["app/javascript/**/*", "package.json", "yarn.lock"].reject { |f| File.directory?(f) }
files.map { |f| File.mtime(f).utc.to_i }.max.to_s
end
def checksum_matches?
last_checksum = File.exists?(checksum_file_path) ? File.read(checksum_file_path) : nil
last_checksum == checksum
end
def write_checksum
File.write(checksum_file_path, checksum)
end
def checksum_file_path
Rails.root.join('tmp', '.webpack-checksum')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment