Best practice or workaround for RSpec specs faking cluster constants

Say I have Car and Mechanic classes. The car has a “run” method. For some reason, a mechanic requires a car. Then I write RSpec specifications. In mechanics, I define fake clans as follows:

class Car; end 

and then drown out the method that the mechanic uses on it. Everything works fine if I run the tests separately. But when I run both tests together (rspec spec / directory /), my Mechanic specifications use the real Car class.

So. I guess this is because ruby ​​classes are "public" and I already loaded the class once for the specification of the car. But is there a better way to do this? What are the best practices for situations like this? Does this mean that my code needs some improvements because it is probably closely related?

I did a quick demo on github: https://github.com/depy/RspecTest

+7
source share
3 answers

This fake class does not work since Ruby classes are open.

One approach that you can use is to use let to initialize the objects the way you want, and if necessary, work with the relation on the front block. Blanks are also welcome inside the blocks. = p

Hope this helps you!

+2
source

I think you need two-layer testing:

  • device specifications: testing each class in isolation
  • integration specifications: testing in general

Given the code as follows:

 class Car end class Mechanic def fix(car) # do something here end end 

For unit specifications, I would drown out the dependencies, for example:

 describe Mechanic do let(:mechanic) { described_class.new } let(:car) { stub(stubbed_method_on_car: 14) } # Or just OpenStruct.new(stubbed_method_on_car: 14) it 'does some stuff' do mechanic.fix(car).should eq true end end 

For integration specifications, I would do the following:

 describe Mechanic do let(:mechanic) { FactoryGirl.create(:mechanic) } let(:car) { FactoryGirl.create(:car) } it 'does some stuff' do mechanic.fix(car).should eq true end end 
+2
source

Rspec has built support for stubbing constants .

0
source

All Articles