【问题标题】:rspec private method instance validation testingrspec 私有方法实例验证测试
【发布时间】:2019-03-30 01:13:29
【问题描述】:

有一个私有方法,代码如下。

attr_reader :some_variable

validate :some_def

def some_def
  unless some_variable.valid?
    some_variable.errors.messages.each do |message|
      errors.add(:some_variable, message)
  end
end

我是 rspec 新手,不熟悉私有方法测试。任何帮助表示赞赏。

我需要覆盖私有方法的行。

【问题讨论】:

  • 看起来像是验证测试 - makandracards.com/makandra/…
  • 嗨,我已经浏览了链接,但无法理解。如果你能解释一下如何。谢谢。
  • IMO 您可以:初始化对象,将some_variable 值设置为无效,然后在您初始化的对象上调用valid?(它应该返回false)。然后,重复相同的操作,但为some_variable 设置正确的值,并检查在调用valid? 时是否得到true
  • 为私有方法编写测试不是一个好习惯。查看有趣的帖子stackoverflow.com/a/105021/398863

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


【解决方案1】:

你可以这样做:

describe 'validations' do
  let(:some_variable_object) { SomeVariable.new } 
  let(:new_foo) { described_class.new(some_variable: some_variable_object) }

  context 'when some_variable is valid' do
    before do
      allow(some_variable_object).to receive(:valid?) { true }
    end

    it 'is valid' do
     expect(new_foo).to be_valid
    end

    it 'does not have errors related to some_variable' do
      expect(new_foo.errors[:some_variables]).to be_empty
    end
  end

那么当some_variable 无效时,你可以做同样的测试来测试相反的结果...... 现在,有一些工具可以帮助您轻松地在规范中设置对象 (FactoryBot)。

【讨论】:

  • 这里的SomeVariable let(:some_variable_object) { SomeVariable.new } 是什么意思?像同一个实例变量?如果是这样,如果它被大写,它会通过未初始化的错误对吗?
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
相关资源
最近更新 更多