>> 1 require 'trip/trip_service' |>> 1 require_relative '../trip/trip_dao' 2 # how to cover an existing code with tests |>> 2 require_relative '../user/user_session' 3 # 1. use a coverage tool |>> 3 require_relative '../user/user' 4 # >> line covered by test run |>> 4 require_relative '../еxceptions/user_not_logged_in_exception' 5 # :( line not covered by test run |>> 5 require_relative '../еxceptions/dependend_class_call_during_unit_test_exceptio 6 # 2. instantiate the object | 6 7 # 3. call the method |>> 7 class TripService 8 # 4. start using just nil for needed params | 8 9 # 5. some objects can't or shouldn't be accessed during test |>> 9 def get_trip_by_user(user) 10 # -> break the dependencies to them |>> 10 trip_list = [] 11 # -> in Ruby/RSpec it is easy to partial stub an existing object |>> 11 logged_user = UserSession.get_instance.get_logged_user 12 # -> we stub UserSession.get_instance to return a double |>> 12 is_friend = false 13 # -> create an expectations for each effective call the code under test | 13 14 # does |>> 14 if(!logged_user.nil?) 15 # 6. when you reach a exit point (like a raise) -> add a expectation to |:( 15 user.get_friends.each do |f| 16 # document the behaviour |:( 16 if(f.equal? logged_user) 17 # 7. after having a test passing that hit an exit point you can continue |:( 17 is_friend = true 18 # with another test seeking for another exit point |:( 18 break 19 # 8. but before continuing spend a little to refactor | 19 end 20 # 9. after you characterized the | 20 end >> 21 describe TripService do | 21 >> 22 subject(:service) { TripService.new } |:( 22 if(is_friend) >> 23 let(:user_session) { double :user_session } |:( 23 trip_list = TripDAO.find_trips_by_user(user) >> 24 it do | 24 end >> 25 expect(UserSession).to receive(:get_instance).and_return(user_session) | 25 >> 26 expect(user_session).to receive(:get_logged_user).and_return(nil) |:( 26 return trip_list 27 | 27 else >> 28 expect do |>> 28 raise UserNotLoggedInException.new >> 29 service.get_trip_by_user nil | 29 end 30 end.to raise_error UserNotLoggedInException | 30 31 end | 31 end 32 | 32 33 end | 33 end ~ | ~ ~ | ~ ~ | ~ ~ | ~ ~ | ~ ~ | ~ ~ | ~ ~ | ~ spec/trip_service_spec.rb [+] 20,34 All lib/trip/trip_service.rb 11,35 All-- INSERT --