steel
steel

Reputation: 12520

Rspec Does Not Recognize Rails's content_tag

I have a Rails (4.2) helper that I am trying to unit test with Rspec 3.

# app/helpers/nav_helper.rb
module NavHelper
  def nav_link(body, url, li_class: "", html: {})
    li_class += current_page?(url) ? " active" : ""

    content_tag(:li, class: li_class) do
      link_to(body, url, html)
    end
  end
end

# spec/helpers/nav_helper_spec.rb
require 'spec_helper'
describe NavHelper do
  describe "#nav_link" do
    it "creates a correctly formatted link" do
      link = nav_link("test", "www.example.com/testing")
      ...
    end
  end
end

This throws the following error when I run the test:

 Failure/Error: link = nav_link("test", "www.example.com/testing")
 NoMethodError:
   undefined method `content_tag' for #<RSpec::ExampleGroups::NavHelper::NavLink:0x007fe44b98fee0>
 # ./app/helpers/nav_helper.rb:5:in `nav_link'

It seems like the Rails helpers aren't available, but I'm not sure how to include them. Regardless, how can I test a helper method that uses content_tag?

Update

Adding include ActionView::Helpers::TagHelper throws the following error

uninitialized constant ActionView (NameError)

Upvotes: 1

Views: 1447

Answers (2)

steel
steel

Reputation: 12520

The issue was the leading line of my spec. I changed require 'spec_helper' to require 'rails_helper' and everything works as expected.

Not the first time that's bitten me, but it was the hardest.

Upvotes: 0

andrewdotnich
andrewdotnich

Reputation: 16794

You need to include the helper that contains the content_tag method in your NavHelper (in this case, TagHelper):

module NavHelper
  include ActionView::Helpers::TagHelper

  # ...
end

It's a good idea to include only the helpers that you need to make things work, as it makes it clear which parts of Rails/ActionView you're using in your helper.

EDIT: Why is this necessary?

When you're testing the helper, you're testing it in isolation from the rest of Rails. That's why RSpec is complaining about the method not being available - it literally isn't there!

Upvotes: 1

Related Questions