Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing current user in helper spec

I have this pretty basic helper which relies on current_user variable provided by Sorcery in controllers and helpers

def current_user_link
    user_link current_user
end

 def user_link(user, html_options = {}, &block)
   link_to user.to_s, user, html_options, &block
 end

How can I test this helper?

describe UsersHelper do
  describe '#current_user_link' do
    it 'should return a link to the current user' do
      expected_link = link_to current_user.name, current_user
      ???

      expect(current_user_link).to eq expected_link
    end
  end

Do I need to stub current_user somehow? Is it even worth testing?

like image 485
just so Avatar asked Jan 20 '16 15:01

just so


1 Answers

This is how I solved it.

describe '#current_user_link' do
  it 'returns a link to the current user ' do
    user = build(:user)
    expected_link = link_to user.name, user
    allow(controller).to receive(:current_user).and_return(user)

    expect(helper.current_user_link).to eq(expected_link)
  end
end

PSA: dont forget to call your method on helper.

like image 168
just so Avatar answered Oct 31 '22 00:10

just so