minimal bdd in ruby

programming ruby

sometimes i want to turn regular sentences into executed code. turns out ruby has my back, it looks like this:

define_method "your sentence here" do
  puts 'your code!'

you can call it with send, and if you know how alias works you can put it all together like this:

require 'test/unit'

alias Given send
alias When  send
alias And   send
alias Then  send

class MinimalBddTest < Test::Unit::TestCase
  def test_minimal_bdd
    Given "You are writing a ruby program"
    When  "You want to write bdd"
    And   "Try define_method"
    Then  "You might like it"

  define_method "You are writing a ruby program" do
    puts 'first method'

  define_method "You want to write bdd" do
    puts 'second'

  define_method "Try define_method" do
    puts 'third'

  define_method "You might like it" do
    assert_equal true, true

so long as you have test-unit installed, you can paste that into irb, hit ctrl-d and see the test output. cool!

if you wanted to get fancy, you’re able to pass named arguments, wrap it in blocks (e.g. rspec’s expect { ... }.to change) and whatever other ruby stuff you enjoy.

this is my logical conclusion to stuff like cucumber, turnip, and simple_bdd. once you’ve made your aliases available in your spec helper, you’re off to the races.

it has a few qualities that i like:

and some tradeoffs:

this is in my ~/.vimrc:

" define_method shortcut
map <Leader>g :s/^\s*\w*\s*\(.*\)/  define_method \1 do\r  end\r/<CR>:noh<CR>

this means a press to <Leader>g will turn:

When "i do a thing"


define_method "i do a thing" do