【问题标题】:RSpec example not working with before_validationRSpec 示例不适用于 before_validation
【发布时间】:2015-04-27 03:40:41
【问题描述】:

我保存了一个相当简单的模型,但遇到了 RSpec 失败,我找不到解决方案。我也在使用 shoulda gem。

CharacterSheet 模型:

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

RSpec 示例:

RSpec.describe CharacterSheet, type: :model do

  let(:character_sheet) { CharacterSheet.new(character_name: "Test Character",
                                                player_name: "Michael",
                                                   strength: 18) }

  describe "attributes" do

    it { expect(character_sheet).to validate_presence_of :character_name }
    it { expect(character_sheet).to validate_presence_of :player_name }
    it { expect(character_sheet).to validate_presence_of :strength }
    it { expect(character_sheet).to validate_presence_of :strength_modifier }

    it "saves attributes" do
      character_sheet.save!
      expect(character_sheet).to be_valid
    end

  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 控制台中手动创建记录,它看起来是正确的。只是测试失败了。

此外,如果我删除 before_validation 调用。唯一失败的是预期的“保存属性”示例。

【问题讨论】:

    标签: ruby-on-rails rspec rspec-rails shoulda


    【解决方案1】:

    好的,首先您必须了解validate_presence_of 匹配器...将该属性的值设置为nil...并测试您是否遇到错误。

    想想这对您的验证前意味着什么。你一无所有...然后在您进行验证之前触发验证前触发器...您尝试从无到有 10 并且它爆炸了。

    我敢打赌,你应该在那里进行测试,以确保它不会做傻事。例如:

    def calculate_strength_modifier
      self.strength_modifier = ((self.strength - 10)/2).floor if self.strength.present?
    end
    

    【讨论】:

    • 谢谢,这解决了第一个故障。对第二个有什么想法吗?
    • 是的。如果您总是在验证之前设置它的值,那么在强度修饰符上使用 validates-presence-of 是没有意义的。它永远不会是 nil - 因此规范永远无法测试您在将其设置为 nil 时是否遇到错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2021-10-27
    相关资源
    最近更新 更多