Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec & Rails: Stub request.path for helper spec

I have this method in ApplicationHelper:

def home_link_class
  classes = ['navbar-brand']
  classes << 'active' if request.path == root_path
  classes
end

I want to test it like this:

describe '#home_link_class' do
  before  { allow(helper.request).to receive(:path).and_return '/some-path' }
  subject { home_link_class }

  it { should eq ['navbar-brand'] }
end

Sadly the stubbing doesn't seem to work, the request object in the helper itself is set to nil, even though in the spec it seems to be an ActionController::TestRequest object.

How do I make sure that request is available in the spec?

like image 601
Joshua Muheim Avatar asked Apr 01 '15 20:04

Joshua Muheim


1 Answers

You need to stub the request itself as well as the return value of path. Define a test double for the request that stubs path:

describe '#home_link_class' do
  let(:request) { double('request', path: '/some-path') }

  before  { allow(helper).to receive(:request).and_return(request) }
  subject { home_link_class }

  it { should eq ['navbar-brand'] }
end
like image 105
infused Avatar answered Oct 20 '22 11:10

infused