title: How to test a random uniq values with rspec
body: <p>I have this code:</p>
  
  <pre><code>def self.generate_random_uniq_code
    code = sprintf("%06d", SecureRandom.random_number(999999))
    code = self.generate_random_uniq_code if self.where(code: code).count &gt; 0
    code
  end
  </code></pre>
  
  <p>The goal is create random codes for a new register, the code can't exist already in the registers
  I'm trying test this way, but when I mock the SecureRandom it always return the same value:</p>
  
  <pre><code>it "code is unique" do
    old_code = Code.new
    old_code.code = 111111
    new_code = Code.new
    expect(SecureRandom).to receive(:random_number) {old_code.code}
    new_code.code = Code.generate_random_uniq_code
    expect(new_code.code).to_not eq old_code.code
  end
  </code></pre>
  
  <p>I was trying to find if there is a way to enable and disable the mock behavior, but I could not find it, I'm not sure I'm doing the test the right way, the code seems no work fine to me.
  Any help is welcome, thanks!</p>