How to set a value in the params hash when testing a Rails helper method with RSpec?
Asked Answered
S

1

26

In Ruby on Rails 4, with RSpec 3.1, how do I set the values of the params hash when testing a Rails helper method?

I want to set params[:search] = 'my keyword search' for use in my helper method and then call it from within the it example block.

spec/helpers/books_helper_spec.rb:

require 'rails_helper'

describe BooksHelper do
  describe "#page_title_helper" do
    let(:params) { {search: 'my keyword search'} }

    it "should read the params hash" do
      expect(helper.params[:search]).to eq "my keyword search"
    end
  end
end

app/helpers/books_helper.rb:

BooksHelper
  def title_helper
    if params[:search]
      "Books related to #{params[:search]}"
    else
      "All Books"
    end
  end
end
Sod answered 4/12, 2014 at 1:53 Comment(0)
F
26

In RSpec 3, the params hash is available on the controller object which is available in helper specs. So, for example, to get at params[:search], say controller.params[:search].

Here's an expanded example, extended from the question.

context "with a params[:search]" do
  it "returns the search term" do
    controller.params[:search] = 'Test Search'
    expect(helper.title_helper).to eq("Books related to #{params[:search]}".html_safe)
    expect(helper.title_helper).to eq("Books related to Test Search".html_safe)
    expect(helper.title_helper).not_to eq("Books related to Bad Value".html_safe)
  end
end
Footplate answered 14/2, 2016 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.