【问题标题】:How do I call a method from an rspec test如何从 rspec 测试中调用方法
【发布时间】:2012-12-23 03:59:01
【问题描述】:

我正在同时学习 Ruby 和 TDD (rspec)。

我写了以下测试:

describe is_eligible do
  it "returns true if the passed in string is not part of a list" do
    result = is_eligible("abc")
    result.should eq(false)
  end
end

正在测试以下代码:

def is_eligible(team_name)
  array = Array.new
  array << "abc" << "def" << "ghi"
  if array.include?(team_name)
    return false
  else
    return true
  end
end

我收到以下错误,但找不到原因。

*/Users/joel.dehlin/top32/lib/ineligible_teams.rb:6:in `is_eligible':参数数量错误(0 代表 1)(ArgumentError)*

感谢任何帮助!

【问题讨论】:

  • 顺便说一句,为了测试真假值,最好使用.should be_trueshould be_false

标签: ruby rspec tdd


【解决方案1】:

问题是describe 方法需要一个字符串或可以评估为字符串的东西。如果你说 "is_eligible" 不带引号,它实际上会尝试调用该方法并得到错误。

describe "is_eligible" do
  it "returns true if the passed in string is not part of a list" do
    result = is_eligible("abc")
    result.should eq(false)
  end
end

【讨论】:

  • 知道了。谢谢!为什么要传入方法名的字符串而不只是方法名?
  • 因为在 ruby​​ 中,方法调用后的括号是可选的(在大多数情况下)——所以当你说“describe is_eligible”时,它实际上与“describe is_eligible()”是一样的。而且因为 describe 只是一个接受参数和块的方法,所以它基本上是“describe(is_eligible()) {...}”。顺便说一句,如果答案解决了你的问题,请采纳。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多