AdvancedLesson 14 of 16
Gems, Bundler & Tests – Ruby
Installing libraries, managing dependencies per project and testing code.
A gem is a Ruby package (library or program). Gems are distributed via RubyGems.org and installed with gem install. Bundler manages the gems of a project via the Gemfile and freezes the exact versions in Gemfile.lock.
gem install rake
gem list
bundle init # creates a Gemfile
bundle add sinatra # adds a gem and installs it
bundle install # installs everything from Gemfile / Gemfile.lock
bundle exec ruby app.rb # runs with exactly the versions of the project
bundle update rack # updates a gem# Gemfile
source "https://rubygems.org"
ruby ">= 3.2"
gem "sinatra", "~> 4.0"
gem "sequel"
gem "sqlite3"
group :development, :test do
gem "minitest"
gem "rubocop", require: false
end~> 4.0 is the "pessimistic version operator": it allows >= 4.0 and < 5.0. With require you load a gem in code, with require_relative a file of your own relative to the current directory. A mini web server with Sinatra:
# app.rb
require "sinatra"
get "/" do
"Hello from Sinatra!"
end
get "/gruss/:name" do
"Hello, #{params[:name]}!"
endIn Ruby, testing is often done with Minitest (in the standard library) or RSpec (readable specifications). Rake automates tasks:
# test/quadrat_test.rb
require "minitest/autorun"
def quadrat(x)
x * x
end
class QuadratTest < Minitest::Test
def test_positiv
assert_equal 16, quadrat(4)
end
def test_negativ
assert_equal 9, quadrat(-3)
end
end# spec/quadrat_spec.rb (RSpec)
RSpec.describe "quadrat" do
it "squares positive numbers" do
expect(quadrat(4)).to eq(16)
end
end
# Rakefile
task default: :test
desc "Run tests"
task :test do
ruby "test/quadrat_test.rb"
end- Check in the Gemfile – and also
Gemfile.lockfor applications (reproducible builds), for gems themselves usually not - bundle exec before commands, so that the project versions are used
- RuboCop checks style and finds typical errors
- YARD/RDoc generate documentation from comments
- A gemspec describes a gem of your own (
bundle gem meingemgenerates a skeleton)
WarningWithout
bundle exec, a different gem version than the one in the lockfile may be loaded by accident – bugs that only occur "on my machine".