2014-02-11 50 views
0

我在Rails应用程序中生成密钥。使用rspec生成测试密钥

self.generate(无参数)方法中生成Key类中的密钥。我可以轻松实现该方法,但如何在rspec中测试我的方法是否尝试重新生成密钥(如果该密钥已存在于我的数据库中)?

回答

1

你可以尝试stub返回你的第一个电话后的一个关键和unstub的方法:

it 'generates a second key if the first one is not unique' do 
    Key.create uid: "be81ed3a9c3a" 
    SecureRandom.stub(:hex).with(6) { 
     SecureRandom.unstub(:hex) 
     "be81ed3a9c3a" 
    } 
    expect(Key.generate.uid).not_to eq("be81ed3a9c3a") 
end