ruby on rails - How to test a random uniq values with rspec -


i have 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 > 0   code end 

the goal create random codes new register, code can't exist in registers i'm trying test way, when mock securerandom return same value:

it "code unique"   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 

i trying find if there way enable , disable mock behavior, not find it, i'm not sure i'm doing test right way, code seems no work fine me. welcome, thanks!

tl;dr

generally, unless testing prng wrote, you're testing wrong behavior. consider behavior you're trying test, , examine alternatives. in addition, six-digit number doesn't have enough of key space ensure real randomness purposes, may want consider more robust.

some alternatives

one should test behavior, rather implementation. here alternatives consider:

  1. use uuid instead of six-digit number. uuid statistically less likely encounter collisions current solution.
  2. enforce uniqueness in database column adjusting schema.
  3. using rails uniqueness validator in model.
  4. use factorygirl sequences or lambdas return values test.

fix spec

if insist on testing piece of code, should @ least use correct expectations. example:

# won't useful, if runs. expect(new_code.code).to_not  old_code.code 

instead, should check equality, this:

old_code = 111111 new_code = code.generate_random_uniq_code new_code.should_not eq old_code 

your code may broken in other ways (e.g. code variable in method doesn't seem instance or class variable) won't guarantee above work, should @ least point in right direction.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -