Book Cover

New e-book released: Mobile Web Patterns with Backbone.js

RSpec with Domino

by on

Using Domino with RSpec is awesome. I'll let the code speak for itself.

We have an html page:

<!doctype html>
<html>
  <head>
    <title>Domino Rspec</title>
  </head>
  <body>
    <h1>Domino Rspec</h1>
    <ul>
      <li><span class='name'>John Doe</span> Age <span class='age'>47</span></li>
      <li><span class='name'>Jane Doe</span> Age <span class='age'>37</span></li>
      <li><span class='name'>Jim Doe</span> Age <span class='age'>27</span></li>
    </ul>
  </body>
</html>

And here is an rspec request spec to test the data:

describe :index_without_domino, :type => :request do
  before do
    visit '/'
  end

  it 'should have three people' do
    page.all('ul li').count.should == 3
  end

  context 'John Doe' do
    subject do
      page.all('ul li').find do |node|
        node.find('.name').text == 'John Doe'
      end
    end

    it 'should have an age of 47' do
      subject.find('.age').text.should == '47'
    end
  end
end

CSS selectors are brittle here, and it's not very rubyish. It's full of html! First, we'll make a domino:

module Dom
  class Person < Domino
    selector 'ul li'
    attribute :name
    attribute :age
  end
end

And then update our test:

describe :index, :type => :request do
  before do
    visit '/'
  end

  it 'should have three people' do
    Dom::Person.count.should == 3
  end

  context 'John Doe' do
    subject { Dom::Person.find_by_name 'John Doe' }
    its(:age) { should == '47' }
  end
end

Because dominos are enumerable ruby objects, we can count them easily. There's also handy attribute finders and accessors. So, a domino can be an rspec subject. Much better!

Full project source code

blog comments powered by Disqus