Ruby on rails RSpec示例在验证前不使用
我保存了一个相当简单的模型,但是遇到了RSpec故障,我无法找到解决方案。我也在使用shoulda宝石 字符表模型:Ruby on rails RSpec示例在验证前不使用,ruby-on-rails,rspec,rspec-rails,shoulda,Ruby On Rails,Rspec,Rspec Rails,Shoulda,我保存了一个相当简单的模型,但是遇到了RSpec故障,我无法找到解决方案。我也在使用shoulda宝石 字符表模型: class CharacterSheet < ActiveRecord::Base validates :character_name, :player_name, :strength, :strength_modifier, presence: true before_validation :calculate_strength_modifier, on: :c
class CharacterSheet < ActiveRecord::Base
validates :character_name, :player_name, :strength, :strength_modifier, presence: true
before_validation :calculate_strength_modifier, on: :create
def calculate_strength_modifier
self.strength_modifier = ((self.strength - 10)/2).floor
end
end
以下是我遇到的失败:
失败:
1) CharacterSheet attributes should require strength to be set
Failure/Error: it { expect(character_sheet).to validate_presence_of :strength }
NoMethodError:
undefined method `-' for nil:NilClass
2) CharacterSheet attributes should require strength_modifier to be set
Failure/Error: it { expect(character_sheet).to validate_presence_of :strength_modifier }
Expected errors to include "can't be blank" when strength_modifier is set to nil,
got no errors
如果我在rails控制台中手动创建一个记录,它看起来是正确的。只是测试失败了
此外,如果我在验证前删除
,
调用。唯一失败的是“保存属性”示例,正如预期的那样。好的,首先您必须了解匹配器的验证\u存在性\u。。。将该属性的值设置为nil。。。并测试是否出现错误
在验证之前,想想这对您的客户意味着什么。你没有力量。。。然后在进行验证之前,将触发before validation触发器。。。如果你想从零开始拿走10,它就会爆炸
我打赌你应该在那里做一个测试,以确保不会做傻事。例如:
def calculate_strength_modifier
self.strength_modifier = ((self.strength - 10)/2).floor if self.strength.present?
end
谢谢,这修复了第一次失败。对第二个有什么想法吗?是的。有没有必要验证存在的强度修改器。。。如果您总是在验证之前设置它的值。它不可能是零-因此规范无法测试在将其设置为零时是否出现错误
def calculate_strength_modifier
self.strength_modifier = ((self.strength - 10)/2).floor if self.strength.present?
end