Tools, gems and testing

The tools around the language turn scripts into a project. Gems and Bundler manage dependencies, Rake runs the tasks, and the command line, the environment and logging are what a program uses to talk to its operator. The second half tests it: Minitest with its assertions, spec style, doubles and stubs, coverage, RSpec, and the testing of files, IO and a web application.

11.1 Gems and Bundler Install gems, describe them in a Gemfile, install the bundle, and lock exact versions. Open 11.2 Rake tasks Automate routine work with small documented Rake tasks. Open 11.3 Environment and CLI Read ENV and ARGV and parse options with OptionParser. Open 11.4 Logging Log to STDOUT with Logger, tune levels, format lines, and rotate log files. Open 11.5 What is inside a gem The four files a gem needs, the gemspec fields that matter, gem build, and installing the result so the command appears on PATH. Open 11.6 Bundler groups and platforms A Gemfile with a development group, bundle install and a local path, the lock file a team commits, and bundle exec for the exact versions. Open 11.7 Rake in depth Tasks with prerequisites, namespaces that group them, file tasks that rebuild only when the source changes, and a default task that runs the suite. Open 11.8 A real CLI with OptionParser Options, subcommands, --help, error messages and exit codes in one file, the skeleton the later projects reuse. Open 11.9 Configuration and environment Defaults in code, a .env file parsed without a gem, ENV on top, and the twelve-factor rule that a build is configured from outside. Open 11.10 Logging in depth Logger with a level and a formatter, one JSON object per event, rotation by size, and the difference between a log line and a debug print. Open 11.11 Testing with Minitest Write your first assertion, run tests with ruby, group with describe, and practice red green refactor. Open 11.12 Minitest assertions assert_equal, assert_raises and refute, with setup and teardown around each test, and one assertion per behaviour. Open 11.13 Testing a web app rack-test against a Sinatra app: a request without a socket, a status assertion, a JSON assertion, and the host check that returns 403 in tests. Open 11.14 Minitest in spec style describe and it, let for lazy setup, expectations such as must_equal and must_raise, and one style per project. Open 11.15 Doubles and stubs Minitest::Mock for an expected call, stub for replacing one method, and a network client tested without a network. Open 11.16 Coverage The coverage library, line coverage for one file, the report a run prints, and the reasons a high percentage is not a good test suite. Open 11.17 RSpec in one lesson A spec file with describe, it and expect, the rspec command, and the same two tests written in Minitest for comparison. Open 11.18 Testing files and IO Dir.mktmpdir for a real folder, teardown that removes it, capture_io for puts, and a test that leaves nothing behind. Open

Lessons