Testing a helper with a block

I’ve been doing a lot of Rspec testing lately. Although I’ve been using it for a while to do BDD I realize that I have not been testing things as well as I should. Yesterday I was trying to add tests for a helper method that ensures the passed in block is only output if the user is logged in and an administrator. It’s a fairly simple helper method.

def admin_accessible(&block)
  if logged_in? and current_user.admin
    concat(capture(&block), block.binding)
  end
end

I stumbled in the test though as I was unsure of how to test a helper that accepts a block. With the help of my colleague we came up with the following two solutions to this problem.

describe ApplicationHelper, 'invoke admin_accessible helper, when logged in as admin' do
  before(:each) do
    @user = mock("user")
    @user.stub!(:admin).and_return(true)

    self.stub!(:logged_in?).and_return(true)
    @block = "Testing admin_accessible"
  end

  # Solution 1
  it 'shall return captured block' do
    html = eval_erb <<-ERB
      <% admin_accessible do %>
        <div><%= @block %></div>
      <% end %>
    ERB
    html.should have_tag('div', @block)
  end

  # Solution 2
  it 'shall return captured block' do
    _erbout = ""
    html = admin_accessible do
       _erbout << "<div>#{@block}</div>"
    end
    html.should have_tag('div', @block)
  end
end

Do you know of a better solution?

Posted August 21st, 2007 at 2:42 pm in Ruby on Rails | Permalink

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Leave a response: