I’m having trouble decoupling my tests from Rails. For instance, how to stub the current_user method (from Devise) that gets called in the helper below?
Helper module:
module UsersOmniauthCallbacksHelper
def socialmedia_name(account)
name = current_user.send(account)['info']['name']
name = current_user.name if name.blank?
name
end
end
Test
require_relative '../../app/helpers/users_omniauth_callbacks_helper.rb'
describe 'UsersOmniauthCallbacksHelper' do
include UsersOmniauthCallbacksHelper
describe '#socialmedia_name(account)' do
it 'should return the users name listed by the social media provider when that name is provided' do
#once I've done away spec_helper, this next line ain't gonna fly.
helper.stub(:current_user) { FactoryGirl.create(:user, facebook: {"info"=>{"name"=>"Mark Zuckerberg"}}) }
socialmedia_name('facebook').should == "Mark Zuckerberg"
end
end
end
How do I stub the current_user method that gets used in the class?
If I were loading Rails, the test could still keep my helper.stub(:current_user). But naturally, that won’t work now since I’m not loading the spec_helper file.
For testing modules, your best choice is to include your helper into a test class, create a new instance, and then stub the methods from there. In addtion, you should move more of the name logic into the model, so that you don’t need to have the helper know about
send(account), and that the return of it is a hash, which has a hash (Law of Demeter). I would want pretty much all of the socialmedia_name method to be in the model. For example: