Testing with Espec and Elixir

Every (new) language comes with a test library, and Elixir is no exception: the name of the built-in one is ExUnit and
you can find the documentation here.

ExUnit is a good start: it is natively integrated in mix and has a few options to customize its output,
still when I use it I feel its assertion syntax is a bit harsh. So I’ve recently started using Espec,
a different testing library ispired by the awesome ruby Rspec testing framework.

Unlike other alternatives this library is not built on ExUnit, so you can’t mix the two assertion syntaxes for example,
but on the other hand you get a more polished finish.

How it works

It’s very easy to add Espec to your project; first create the project:

mix new espec_demo --module EspecDemo

then edit the mix.exs file as follows:


 def deps do
  [
    ...
    {:espec, "~> 0.8.11", only: :test}
  ]
end

def project do
  [
    ...
    preferred_cli_env: [espec: :test]
  ]
end

The shell command to run the specs is MIX_ENV=test mix espec, but thanks to the preferred_cli_env: [espec: :test] directive
you can avoid prepending MIX_ENV=test everytime you run them.

Run mix deps.get in order to download the dependecies code then run mix espec.init in order to bootstrap Espec.
This will generate a few files under the spec folder: spec_helper.exs which contains some configuration and
example_spec.exs, which includes a brief example of what can be done with Espec:


defmodule ExampleSpec do
  use ESpec

  before do
    answer = Enum.reduce((1..9), &(&2 + &1)) - 3
    {:shared, answer: answer} #saves {:key, :value} to `shared`
  end

  example "test" do
    expect shared.answer |> to(eq 42)
  end

  context "Defines context" do
    subject(shared.answer)

    it do: is_expected.to be_between(41, 43)

    describe "is an alias for context" do
      before do
        value = shared.answer * 2
        {:shared, new_answer: value}
      end

      let :val, do: shared.new_answer

      it "checks val" do
        expect val |> to(eq 84)
      end
    end
  end

  xcontext "xcontext skips examples." do
    xit "And xit also skips" do
      "skipped"
    end
  end

  pending "There are so many features to test!"
end

If you used Rspec with ruby you should feel at home with Espec: before, subject, context, describe, let, pending, expect are all there
to make you feel comfortable, and if it wasn’t for a few details you could think this was actually ruby code 😉

Leave a Reply

wpDiscuz