The HTTP Mocks In Rspec

Sometimes, when you write rspec to test some method, and the method context like that :

For now, you wanna test get_title method to check the title string you get is expected what you want, so we write rspec code like that :

But now there’s some issue in here, as you see, the rspec will create a new real internet connection to get response when everytime you run the test.

It bring massive cost when your project grow, casue the internet connection time, in Scrum, we need use iterative development to make faster progress in our development period, this mean we will run test againe and againe very quickly, so if your tests exist very much real internet connect like the rspec example we write in here, it will be a massive trouble in future.

How can I do? There’re two several ways that we can solve this issue :

  • Using Rspec-Mocks to stub get_response_through_internet like that, but it’s not a good way, as you see, you need write a massive content what you want in your codebase and actually you didn’t really do the test in get_response_through_internet method cause you have mocked the method.
  • Using WebMock gem, the gem can help you intercept HTTP request and return fake data what you write like that, the disadvantage is the same as Mock that you need write your own response content, but at least it really test get_response_through_internet method.
  • The best way I recommend is using VCR gem, the gem use Lazy Evaluation that mean it help you build real response throught internet when you first call get_response_through_internet method the save the respone in a dircetory what you specify, when second call coming, it will take the record saved for you instead of create a real internet connect again, the benefit is apparent you don’t need write massive content anymore and it still keep efficient.

All detail of gems I used are in the below.