Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 585
sealocal Avatar asked Dec 04 '14 01:12

sealocal


1 Answers

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 
like image 158
Dave Schweisguth Avatar answered Sep 28 '22 04:09

Dave Schweisguth