Friday, 21 December 2012

Poor man's guide to managing Ruby versions

Understanding the guts of Ruby Version Management by rolling your own

I've been tinkering with a fresh install of Ubuntu 12.10, setting up a nice clean development environment. One of the first things to do, of course, is implement some sort of Ruby version management. RVM and rbenv seem to be the clear winners in this arena, though there are a lot of tools out there that do a similar job.

Writing your own version management for your Rubies isn't actually all that difficult. At it's core, we need need two things:

  • A way to segregate the executables of the various versions
  • A way to call the versions at will

Segregating versions is trivial - working with files and folders, we can put the various versions into named directories.

Actually executing our different versions is not all that difficult either. One way would be to create aliases with version numbers and explicitly call those when we want to use them. The more popular way, however, is to manipulate our PATH variable. The PATH variable tells our operating system where to look for executables when we, for example, type a command into the terminal. The first match it hits is the one it uses.

Using this idea, it isn't all that difficult to set up our own poor man's Ruby version management.

But Why?

Why would anyone want to do this when there are already tested and stable versions out there?

Simple - because we can! Really, though, this is an experiment, a little tinkering that will further your own understanding and even if you don't actually use this for your own version management, it will give you a better appreciation of what's going on behind the scenes of your favourite Ruby environment management system.

Step 1 - Get and compile your rubies

To pull off this experiment, we are going to need two distinct versions of Ruby. I'm going to use a 1.9 and a 1.8. The advantage is it is easy to test which we have running with some simple Ruby string commands because of the changes between the versions.

Download Ruby 1.9.3-p327 and Ruby 1.8.7-p371. Now extract the archives:

$ tar -zxvf ruby-1.9.3-p327.tar.gz
$ tar -zxvf ruby-1.8.7-p371.tar.gz

Step 2 - Set up some directories

I'm going to create a directory called ".pmrbm" in which to stash my Ruby versions. Inside that directory, I'll create an explicit 1.8.7-p371 and 1.9.3-p327 directory:

$ mkdir -p $HOME/.pmrbm/1.8.7-p371
$ mkdir $HOME/.pmrbm/1.9.3-p327

Step 3 - Compile

Compiling Ruby from source might sound scary if you've never done it before, but really it's a walk in the park. We should have two directories in our downloads folder (from the unarchiving we did earlier) - one for the 1.8.7 and one for the 1.9.3 versions. As we compile our versions, we will pass in the path into which we want the compiled Ruby to end up with the "--prefix" command:

$ cd ruby-1.8.7-p371
$ ./configure --prefix=$HOME/.pmrbm/1.8.7-p371
$ make
$ make install

And you should have Ruby 1.8.7-p371 installed. Now we do the same for our 1.9.3-p327 version, but obviously substituting our 1.9.3 specific paths in:

$ cd ruby-1.9.3-p327
$ ./configure --prefix=$HOME/.pmrbm/1.9.3-p327
$ make
$ make install

We've now got two versions of Ruby compiled on our machine.

Win

How on earth are we going to use our Ruby versions? Well, if you are paranoid, you could cd into the various directories and confirm that Ruby is installed and running in those directories. I'll skip that step and simple start modifying my PATH. My system had a fresh install of Ubuntu on it, with no system Ruby installed, so at this point, even though I've compiled two different versions of Ruby, if I try to interrogate the version of Ruby on my system, I will get an error:

$ ruby -v
$ The program 'ruby' can be found in the following packages:
...

Obviously, I'm not going to install Ruby from apt-get, because that would defeat the object of this exercise. Instead, I'll type the following:

$ export PATH="$HOME/.pmrbm/1.8.7-p371/bin:$PATH"

And now when I can get the Ruby version (note I'm in my home directory, but you can be in any directory you want, the PATH will make sure that the OS can find your 1.8.7 version of Ruby:

$ ruby -v
$ ruby 1.8.7

If I run some code in irb, I can confirm that I'm running 1.8.7, because of the way it handles single string characters:

$ irb
> "cat[1]"
=> 97

Great, but what about 1.9.3? Easy as pie - simply change your PATH:

$ export PATH="$HOME/.pmrbm/1.9.3-p327/bin:$PATH"

Again, check the version and confirm with a little bit of single string manipulation:

$ ruby -v
$ ruby 1.9.3p327
$ irb
> "cat[1]"
=> "a"

Note that I was pretty sloppy there with the PATH. For example, if you were to examine your PATH variable at this point, you should see something like(your path will obviously vary based on your system setup):

$ echo $PATH
/home/rubyflewtoo/.pmrbm/1.9.3-p327/bin:/home/rubyflewtoo/.pmrbm/1.8.7-p371/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin/usr/bin:/sbin

See, both the ruby versions are present in the path, though at the moment, ruby is reporting it is version 1.9.3 because the first path that the OS finds Ruby in is 1.9.3-p327/bin, so it simply ignores the 1.8.7 path later in our environment variable. You can, if you feel like playing with this, move the 1.9.3 directory, and test again to see that the OS would then pick up the 1.8.7 version. So

$ mv ~/.pmrbm/1.9.3-p327 ~/.pmrbm/1.9.3-p327.back
$ export PATH=$PATH
$ ruby -v
ruby 1.8.7

Obviously, a neater solution would be to remove the portions of the PATH that are not needed rather than continually pre-pending to it

What now?

Now you should trash all of the above and go use one of the existing stable and actively maintained solutions. A few options:

Tuesday, 11 December 2012

Rails 3.2, MiniTest Spec and Capybara

What do you do when you love your spec testing with Capybara but you want to veer off the beaten path of Rspec and forge ahead into MiniTest waters? Follow along, and you'll have not one, but two working solutions.

The setup

Quickly now, let's throw together an app to test this out. I'm on rails 3.2.9.

$ rails new minicap

Edit the Gemfile to include a test and development block

group :development, :test do
  gem 'capybara'
  gem 'database_cleaner'
end

Note the inclusion of database_cleaner as per the capybara documentation

And bundle:

$ bundle

We will, of course, need something to test against, so for the sake of it, lets throw together a scaffold, migrate our database and prepare our test database all in one big lump. If you are unclear on any of this, go read the guides.

$ rails g scaffold Book name:string author:string
$ rake db:migrate
$ rake db:test:prepare

Make it minitest

To make rails use minitest, we simply add a require statement to our test_helper.rb:

require 'minitest/autorun'
require 'capybara/rails'

We can add in a quick integration test to verify that everything is working correctly up to this point:

$ touch test/integration/book_spec.rb

If you are that way inclined, you could create an "acceptance" directory and pop your tests in there instead. I'm not too bothered by the naming right now, because this is a proof of concept.

Now edit the book_spec.rb file we created

require 'test_helper'

describe Book do
  it "creates a new book" do
    1.must_equal 1
  end
end

Running this passes nicely:

$ ruby -Itest test/integration/book_spec.rb

Setup is complete. We have a nice little project with which to experiment.

Failing to use Capybara

At this point we can try to throw in some navigation from the Capybara DSL to see if it will work. Update book_spec to include "visit":

describe Book do
  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

and you will get an error when you run the test again - something to the effect of

$ NoMethodError: undefined method 'visit' for #<#:0x43c20f0>

Fix what you break

The rest of this post will focus on getting this small piece of code to work. I've found two ways so far. I'll present both and you can decide which you prefer.

The way of the Severed Rodent Hand

Pinched pretty much verbatim from the excellent rstat.us project, the Way of the Severed Rodent Hand uses a module. Working from the principle of the simplest thing that works, I'm going to start out in book_spec.rb and do this:

describe Book do
  Include Capybara::DSL
  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

This produces a passing test. Dig a little deeper though and we will notice that the Capybara documentation suggests using a teardown method to instruct DatabaseCleaner to clean our database as well as reset sessions. MiniTest supports teardown hooks, but we will use and after method to start with:

describe Book do
  Include Capybara::DSL
  after do
    DatabaseCleaner.clean       # Truncate the database
    Capybara.reset_sessions!    # Forget the (simulated) browser state
    Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
  end

  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

Our tests work - and everything is right with the world.

Sever

Of course, no self respecting rubyist is going to leave this code as it stands. As soon as we add another resource, we will be duplicating the after block. Instead, we are going to sever that code and create a module, just like rstat.us. I'm going to put this into my test_helper file for simplicity but on a larger project, you might prefer to use a dedicated integration_helper or acceptance_helper:

module IntegrationTestHelper
  include Capybara::DSL
  
  def teardown
    DatabaseCleaner.clean       # Truncate the database
    Capybara.reset_sessions!    # Forget the (simulated) browser state
    Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
  end
end

I've also taken the opportunity to move the code from "after" into a teardown hook - MiniTest will pick this up for us because it is just awesome! To complete this refactor, we must include our module into our spec. Open up book_spec again and change it a little:

describe Book do
  include IntegrationTestHelper

  it "creates a new book" do
    puts 'create'
    visit('/books/new')
    1.must_equal 1
  end
end

Our tests still pass. We are golden.

The Classical method

Using a module as we just did works well. Nothing to fix there. However there's a trade-off, we have that little "include IntegrationTestHelper" in all our test that need access to Capybara's DSL. We can swap out this inconvenience for a slightly different one - this one based on classes instead of modules. It has it's own inconvenience, but you pay's your money, you takes your choice.

Set up a class

This method relies on a class in our test_helper - let's code it up like this:

class IntegrationHelper < MiniTest::Spec
  include Capybara::DSL
 
  after do
    DatabaseCleaner.clean
    Capybara.reset_sessions!
    Capybara.use_default_driver
  end
end
MiniTest::Spec.register_spec_type( /Integration$/, IntegrationHelper )

The magic here is the last line - this basically says that for any test that is described as "Integration", set the parent to IntegrationHelper (and thus inherit all the goodness of the DSL and the after block). Of course this magic can only be hooked up if we change book_spec to include the word Integration in our initial describe:

describe 'Book Integration' do
  #include IntegrationTestHelper

  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

This passes. Changing your register_spec_type regex to something like "/Integration$/i" and you will have a case insensitive match if you prefer to use normal english casing on subsequent words.

Wrap up

Two methods, both work. On the one hand, you have to "include", on the other hand you have to describe correctly but you get a class hierarchy. I know religious wars have been started over less, but I encourage you to try both and go with your gut. If you have a better/another way, drop me a comment and share the love.