【问题标题】:how to write rspec for method如何为方法编写rspec
【发布时间】:2017-08-23 02:09:16
【问题描述】:

我在可编程文件夹中有以下代码

module Programmability
  module Parameter
    class Input < Parameter::Base
      attr_reader :args

  def initialize(name, type, **args)
    super(name, type)
    @args = args
  end

  def value=(val)
    if val
      val = convert_true_false(val)
--- some code ----
    end
    @value = val
  end      


  def convert_true_false(val)
    return val unless @args[:limit] == 1
    if [:char].include?(@type) && val == 'true'
      'Y'
    elsif [:char].include?(@type) && val == 'false'
      'N'
    elsif [:bit].include?(@type) && val == 'true'
      1
    elsif [:bit].include?(@type) && val == 'false'
      0
    end
  end
end
  end
end

我正在尝试为方法 convert_true_false 编写 rspec。我是 rspec 的新手。任何帮助表示赞赏。

我试过这样做

   context 'returns Y if passed true'
    input = Programmability::Parameter::Input.new(name, type, limit)

      it 'returns Y' do
        name = 'unregister_series'
        type = ':char'
        limit = 1

        expect(input.value = 'true' ).to eq('Y')
      end
  end

但它没有拾取极限值。当它到达 convert_true_false 方法时,它就会出现,因为 @args[:limit] 是 nil

谢谢

【问题讨论】:

  • 你有没有尝试过?
  • 是更新的问题
  • 你能在你的规范中添加创建input的代码吗?
  • 抱歉错过了。已添加
  • args 是关键字参数。因此你应该做Input.new(name, type, limit: limit)。它根本不应该让你创建对象。

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


【解决方案1】:

问题在于 setter 总是返回传递的值:

class Test
  def foo=(foo)
    @foo = foo + 100
    return 42
  end
end

puts (Test.new.foo = 69) # 69

要解决它,只需检查分配后的值:

# instead of
expect(input.value = 'true').to eq 'Y'

# do
input.value = 'true'
expect(input.value).to eq 'Y'

【讨论】:

  • 输入返回 <:parameter::input:0x007f99573785a0>1}, @value="Y"所以我确实期望(input.value).to eq('Y')但得到错误预期:“Y”得到:“N'Y'”
猜你喜欢
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多