1

I have a Rails 4.2 application that does different business depending on host name. I know this practice is frowned upon in certain circles but I managed to get the same code base working on about 400 websites, the amount of time|cpu|ram|db|money|squirrels saved is tremendous.

Eg: For www.example.com for user john@doe.com it might show Product 1 with a $5000 price tag;

For www.blah.com for all usrs it might show Product 1 with a $123 price tag. And a shipping fee of $400.

This is all based on host name and a number of variables stored into session when users visit and/or log in to the website.

I'd like to write a bunch of specs to test various aspects of the application but I need to be able to set the request.host, format and some things in the session.

How do I get this done?

Later edit:

I managed to do a find and replace through the source code and get the session/request access done from within some helper methods. Now I can stub within my specs as follows:

            allow_any_instance_of(ApplicationHelper).to receive(:detect_user_info_by_ip).with("ip").and_return( { :provider => "dummy", :ip => "127.0.0.1", :lat => 1.0, :latitude => 1.0, :lon => 2.1, :long => 2.1, :longitude => 2.1, :regi
on => "EU", :country => "GB", :city => "Testville", :country_iso2 => "GB", :success => true} )
            allow_any_instance_of(ApplicationHelper).to receive(:detect_user_info_by_ip).and_return( { :provider => "dummy", :ip => "127.0.0.1", :lat => 1.0, :latitude => 1.0, :lon => 2.1, :long => 2.1, :longitude => 2.1, :region => "EU",
 :country => "GB", :city => "Testville", :country_iso2 => "GB", :success => true} )

Bottom line is: easier to refactor and stub than access the request and session objects from within specs.

Nick M
  • 2,424
  • 5
  • 34
  • 57
  • 1
    Possible duplicate: https://stackoverflow.com/questions/598933/how-do-i-change-the-default-www-example-com-domain-for-testing-in-rails – Msencenb Sep 11 '18 at 22:23
  • Chosen answer does not clarify where that line of code goes and when, also does not cover session. – Nick M Sep 11 '18 at 22:36
  • What type of spec? integration? controller? view? some types of specs does not run in the context of a request or session. Personally I would move the code where you use request and session to helper methods since those are easier to stub (instead of setting the request or session values, you can just stub the helpers to return whatever you need). – arieljuod Sep 11 '18 at 22:49
  • Controller and views. Looking for a quick solution so I won’t have to refactor certain parts of the application. – Nick M Sep 11 '18 at 23:35
  • Ariel can you please post an answer as to how to properly stub helper methods. Looks like I was able to move most of session/request reading into helpers with some find and replacing through the source. – Nick M Sep 12 '18 at 15:28
  • @NickM if you want a real answer please post code. This is too broad. – Msencenb Sep 12 '18 at 21:34

0 Answers0