Writing a spec for helper with Ruby on Rails and RSpec

Viewed 16860

I have been writing specs for controllers and models, but I have never written a helper spec. I have no idea where I start.

I have the following snippet in application_helper.rb

  def title(page_title)
    content_for(:title) { page_title }
  end
  • How should I write a helper spec on the code?
  • Also if there's any open-source Rails app to show good helper testing/specing, do let me know.
5 Answers

It is also possible to include your helper inside the test class as follows:

 describe ApplicationHelper do
   helper ApplicationHelper

   it "should work" do
     my_helper_method("xyz").should == "result for xyz"
   end
 end

Worked for me with Rails 3.

RSpec should automatically load classes and modules from your rails environment when you 'describe' them, so a valid helper spec could be:

#deleted

But remember that bdd is not testing every single method but the behaviour of your application.

edit:

as @Ken said, my spec was not correct, It was definately the wrong way to do it. So I came out with a Request spec solution that I like more than an Helper spec.

# inside your helper
def title=(page_title)
  content_for(:title) { page_title }
end

# views/resource/index.html.erb
<% title = "foo" %>

# views/layouts/application.html.erb
<%= yield :title %>

# request spec
require 'spec_helper'

describe YourResource do
  it "should output content for title"
    get "/resource"
    response.body.should =~ /<title>foo<\/title>/
  end
end

otherwise, if you want to test only the helper behavior (because it's critical or because you don't have any views) @Ken's solution is better.

Related