当使用外键测试模型时,我想断言模型不能用不存在的外键保存。
用于测试的示例类:
class Wheel
belongs_to: car
end
所以,单元测试应该是这样的:
def test "a wheel must belong to an existent car"
@wheel = Wheel.new
@wheel.car_id = INEXISTENT_CAR_ID
assert !@wheel.save
end
找到有效的 INEXISTENT_CAR_ID 的最佳方法是什么(已知灯具加载了随机 ID)?
最佳答案
我喜欢 Chowlett 的方法。但是它失败了,如果根本没有记录,那么你可能想写
@wheel.car_id = Car.order("id").last.try(:id).to_i + 1
关于ruby-on-rails - Rails 测试单元 : How to find an unused id for a model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7404804/