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.
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
BooksHelper
def title_helper
if params[:search]
"Books related to #{params[:search]}"
else
"All Books"
end
end
end
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