vendredi 26 juin 2020

¿Is it safe to modify classes for example using "class_eval" (Ruby) in the tests suite?

In other words: ¿It there a chance for a class modification (on tests) to affect production code?

(This code example is using Rspec for testing in a Rails app)

My controller example

In this controller ExternalModel is created. Then it's "inscription" method is called and the results are assigned to a variable. It uses the result for other actions on the controller method.

class WebpayController < ApplicationController
  def callback_page
    external_model = ExternalModel.new(argument)
    result = external_model.inscription

    render_error_json && return unless result['error_desc'].eql? 'OK'
    TransactionModel.create(token: result['token'])
  end
end

My Spec example

In the spec I modify ExternalModel so it returns what I want when calling the .inscription method:

ExternalModel.class_eval {
      def inscription(_fake_arguments)
        {
          'error_desc' => 'OK',
          'token' => '1234'
        }
      end
    }

This is the entire spec:

RSpec.describe 'Webpay management', type: :request do
  context 'callback_page' do
    it 'creates a transaction' do
      ExternalModel.class_eval {
        def inscription(_fake_arguments)
          {
            'error_desc' => 'OK',
            'token' => '1234'
          }
        end
      }

      expect {
        post(callback_page_path)
      }.to change(TransactionModel.all, :count).by(1)

      expect(response).to render_template(:callback_page)
    end
  end
end

Aucun commentaire:

Enregistrer un commentaire