RSpec 从输入框中检索值且值为数字时,预期表现异常

RSpec expectation is behaving strangely when retrieving value from input box and the value is a number

我有一个辅助方法,可以在输入框中设置一个值,然后验证文本。但是,如果值为数字,则此操作失败。它看起来像:

def fill_in_value(label, text_input)
  textarea = find(locator of the input box, using the label passed into this method)
  textarea.set(text_input)
  textarea.value.should == text_input
end

但是,如果 text_input 是一个数字,rspec 预期会失败 expected: 1 got: "1" (using ==)

我可以通过执行以下操作来解决此问题:

text_input = text_input.to_s if text_input.is_a? Numeric

但这看起来真的很笨拙。有没有办法让我正确评估插入输入框的文本?

任何 HTML 字段的值都将是字符串(即使它是 "number" 字段)。您不需要在 text_input 上做条件,只需始终做 text_input = text_input.to_s,因为正如您的参数名称所暗示的那样 - 它应该是文本。此外,你永远不应该做 textarea.value.should == ... 那是易碎测试的主要方法。相反,您应该使用 Capybara

提供的匹配器
textarea.should match_selector(:field, with: text_input.to_s)

或者如果使用 RSpec

的较新 expect 语法
expect(textarea).to match_selector(:field, with: text_input.to_s)