Skip to content

Instantly share code, notes, and snippets.

@naps62
Created April 19, 2017 13:36
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save naps62/a7dcce679a45592714ea6477108f0419 to your computer and use it in GitHub Desktop.
Save naps62/a7dcce679a45592714ea6477108f0419 to your computer and use it in GitHub Desktop.
Run webpacker before test suite, only if a test tagged with JS is selected
# spec/support/webpack.rb
module WebpackTestBuild
TS_FILE = Rails.root.join("tmp", "webpack-spec-timestamp")
class << self
attr_accessor :already_built
end
def self.run_webpack
puts "running webpack-test"
`RAILS_ENV=test bin/webpack`
self.already_built = true
File.open(TS_FILE, "w") { |f| f.write(Time.now.utc.to_i) }
end
def self.run_webpack_if_necessary
return if self.already_built
if timestamp_outdated?
run_webpack
end
end
def self.timestamp_outdated?
return true if !File.exists?(TS_FILE)
current = current_bundle_timestamp(TS_FILE)
return true if !current
expected = Dir[Rails.root.join("app", "javascript", "**", "*")].map do |f|
File.mtime(f).utc.to_i
end.max
return current < expected
end
def self.current_bundle_timestamp(file)
return File.read(file).to_i
rescue StandardError
nil
end
end
RSpec.configure do |config|
config.before(:each, :js) do
WebpackTestBuild.run_webpack_if_necessary
end
end
@TaniaSwan
Copy link

Worked for me.

@bbugh
Copy link

bbugh commented Oct 1, 2018

Thanks for this! It works great.

Using the Rails built-in command Webpacker.compile in place of the backtick shell command may behave better. It returns a boolean based on success, and you can add better error handling to it.

puts "running webpack-test"
unless Webpacker.compile
  raise "Error: webpacker failed to build. Run 'bin/webpack', fix any issues, and try again."
end
self.already_built = true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment