我正在开发的游戏中有以下方法:
def search
if rand(5) == 0
weapon = Weapon.offset(rand(Weapon.count)).first
users_weapon = UsersWeapon.create(user_id: self.id, weapon_id: weapon.id, ammo: weapon.max_ammo)
self.users_weapons << users_weapon
{ :success => 'true', :weapon => users_weapon }
else
{ :success => 'false' }
end
end
如你所见,我有两个rand
's 。
现在,当我尝试使用 rspec 对其进行测试时,我想测试以下内容:
context 'when searches location' do
subject(:user) { FactoryGirl.create :User }
before { FactoryGirl.create :knife }
before { FactoryGirl.create :pistol }
context 'when finds knife' do
before { srand(2) }
it { user.search[:weapon].weapon.name.should == 'Knife' }
end
context 'when finds pistol' do
before { srand(3) }
it { p user.search[:weapon][:name].should == 'Pistol' }
end
无论我在srand
这里传递什么,它只能以以下两种方式之一起作用:
a)返回Pistol
或
b)返回 nil。
我想rand
独立地存根这些 s。我不想weapon
在每种情况下只播种一个,因为我想实际测试随机武器选择。我该如何执行?