RSpec Mock Object Example

前端 未结 5 1035
说谎
说谎 2021-01-30 13:13

I am new to mock objects, and I am trying to learn how to use them in RSpec. Can someone please post an example (a hello RSpec Mock object world type example), or a link (or any

5条回答
  •  醉话见心
    2021-01-30 13:51

    I don't have enough points to post a comment to an answer but I wanted to say that the accepted answer also helped me with trying to figure out how to stub in a random value.

    I needed to be able to stub an object's instance value that is randomly assigned for example:

    class ClumsyPlayer < Player do
    
      def initialize(name, health = 100)
        super(name, health)
        @health_boost = rand(1..10)
      end
    end
    

    Then in my spec I had a problem on figuring out how to stub the clumsy player's random health to test that when they get a heal, they get the proper boost to their health.

    The trick was:

    @player.stub!(health_boost: 5)
    

    So that stub! was the key, I had been just using stub and was still getting random rspec passes and failures.

    So thank you Brian

提交回复
热议问题