Implement and Test in One File with bundler/inline and rspec/autorun
Posted on by Gentaro "hibariya" Terada
Sometimes I want to create a tiny one-off script that intended to run on a sandbox environment like a Docker container and needs only one file. Most of the time, I also need test frameworks to do some refactoring. It can be done with
require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'rspec' end def doit 'return a string' end require 'rspec/autorun' RSpec.describe '#doit' do example do expect(doit).to be_a(String) end end
Usually, Bundler reads the dependencies from
Gemfile. However, we can forgo this file by using
gemfile block instead. As running the script, Bundler will install gems that are required by the block but not installed in the system. So the initial run may take a little longer time for installation. Note that you cannot place
require 'rspec/autorun' before the
gemfile block since some of the dependencies might not be installed yet before that.
You can run it as an ordinary Ruby script and let Bundler takes care of the dependencies.
root@a44fe6f150cc:/work# ruby example_script.rb . Finished in 0.00195 seconds (files took 0.05462 seconds to load) 1 example, 0 failures
By the way, the same thing can be done with the combination of Bundler and Minitest.
gemfile do source 'https://rubygems.org' - gem 'rspec' + gem 'minitest' end def doit 'return a string' end -require 'rspec/autorun' +require 'minitest/autorun' -RSpec.describe '#doit' do - example do - expect(doit).to be_a(String) +class TestDoit < Minitest::Test + def test_doit + assert_equal(String, doit.class) end end
bundler/inline allow us to declare the dependencies without creating a
Gemfile, install them automatically. We don't have to create a directory for the script and run
bundle install. It's useful for a tiny one-off script.