Posted 4 months ago. Visible to the public.

RSpec: How to turn off partial double verification temporarily

With RSpec 3.6.0 you can turn of partial double verification for single mocks. This might be handy in case you are testing helpers in Rails, where you sometimes rely on methods defined in the application controller (e.g. current_user and current_power).

Example

Copy
class ApplicationController def current_user User.find_by(session[:user_id]) end helper_method :current_user end module UsersHelper def user_display_name [current_user.first_name, current_user.last_name].join(' ') end end

Unit test with error

Copy
describe UsersHelper do describe '#user_display_name' do it 'returns the first and last name of a user' do user = FactoryBot.create(:user) allow(helper).to receive(:current_user).and_return(user) expect(helper.user_display_name).to eq('Jim Knopf') end end end

Error: <helper> does not implement: current_user

Unit test fixed with without_partial_double_verification

Copy
describe UsersHelper do describe '#user_display_name' do it 'returns the first and last name of a user' do user = FactoryBot.create(:user) without_partial_double_verification do allow(helper).to receive(:current_user).and_return(user) end expect(helper.user_display_name).to eq('Jim Knopf') end end end

Note: This is just one over multiple options to solve the problem. You might also extract controller methods to helpers or pass in required objects as arguments.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Emanuel De
Last edit:
19 days ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more