Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active December 19, 2016 09:27
Show Gist options
  • Save tobiashm/5dd884c8e399b342f36cdf8a5b7cd249 to your computer and use it in GitHub Desktop.
Save tobiashm/5dd884c8e399b342f36cdf8a5b7cd249 to your computer and use it in GitHub Desktop.
Karma on Rails

Use Karma.js with Ruby on Rails (Sprockets)

Inspired by http://monterail.com/blog/2014/karma-on-rails/

This basically allows you to reference your application JS files, which are generated by Sprockets, in the Karma config like this:

files: [
  '<%= require("application.js") %>',
  '<%= require("other.js") %>',
  'static/files/**/*.js'
]

Add PhantomJS gem to your Gemfile: gem "phantomjs"

Install Karma.js and the PhantomJS runner: npm install --save-dev karma karma-phantomjs-launcher

// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '<%= Rails.root %>',
// list of files / patterns to load in the browser
files: [
'<%= require("application.js") %>',
'spec/javascripts/**/*_spec.js'
],
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS']
// The rest of your config goes here
});
};
require "karma_runner"
namespace :karma do
task start: :environment do
KarmaRunner.new.start
end
task run: :environment do
exit KarmaRunner.new.start("--single-run")
end
end
require "erb"
require "phantomjs"
class KarmaRunner
CONFIG_FILE = "karma.conf.js"
def start(args = nil)
@tempfiles = []
Tempfile.open(CONFIG_FILE) do |f|
f.write config_file
f.flush
env = { "PHANTOMJS_BIN" => Phantomjs.path }
system(env, "$(npm bin)/karma start #{f.path} #{args}")
end
ensure
@tempfiles.each do |file|
file.close
file.unlink
end
end
def config_file
template = Rails.root.join("spec", "#{CONFIG_FILE}.erb")
ERB.new(template.read).result(binding)
end
def require(src)
f = Tempfile.new(src)
@tempfiles << f
f.write Rails.application.assets.find_asset(src).to_s
f.flush
f.path
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment