【问题标题】:wrong number of arguments ruby rspec参数数量错误 ruby​​ rspec
【发布时间】:2013-09-23 04:36:41
【问题描述】:

我正在尝试使用 rspec 为我的代码编写单元测试。我不断收到“错误数量的参数”错误:

class MyClass
  attr_accessor :env, :company,:size, :role, :number_of_hosts,:visability

  def initialize(env, company, size, role, number_of_hosts, visability)
    @env, @company, @size, @role, @number_of_hosts, @visability =  env, company, size, role, number_of_hosts, visability
  end




end

这是我的测试:

require_relative "../lib/MyClass.rb"

 describe MyClass do
    it "has an environment" do
        MyClass.new("environment").env.should respond_to :env
    end

    it "has a company" do
        MyClass.new("company").company.should respond_to :company
    end

...

当我运行 rspec 时,我得到:

1) MyClass has an environment
     Failure/Error: MyClass.new("environment").env.should respond_to :env
     ArgumentError:
       wrong number of arguments (1 for 6)
     # ./lib/MyClass.rb:4:in `initialize'
     # ./spec/MyClass_spec.rb:5:in `new'
     # ./spec/MyClass_spec.rb:5:in `block (2 levels) in <top (required)>'

...

我错过了什么?

编辑

Sergio 帮助感谢...但是

Sergio 的回答奏效了……尽管我还有一个问题:

给定班级:

class Team
    attr_accessor :name, :players

    def initialize(name, players = [])
        raise Exception unless players.is_a? Array

        @name = name
        raise Exception if @name && has_bad_name

        @players = players
    end

    def has_bad_name
        list_of_words = %w{crappy bad lousy}
        list_of_words - @name.downcase.split(" ") != list_of_words
    end

    def favored?
        @players.include? "George Clooney"
    end

end

和规格...

require_relative "../lib/team.rb"

describe Team do
    it "has a name" do
        Team.new("random name").should respond_to :name
    end

    it "has a list of players" do
        Team.new("random name").players.should be_kind_of Array
    end

...

测试通过而没有相同的错误...(这工作正常:Team.new("random name"))

有什么解释吗?

【问题讨论】:

  • 您还缺少 5 个构造函数的参数。
  • 你的意思是,MyClass.new("company","blah","blah","blah","blah") ??
  • 是的,类似的
  • 我编辑了我的问题...你能解释一下为什么我需要添加多个参数吗?
  • -1 用于在发布问题后更改问题,而不是针对您遇到的其他问题发布新问题。这在这里被认为是粗鲁的。

标签: ruby unit-testing rspec


【解决方案1】:

这是错误MyClass.new("environment")。正如你写的def initialize(env, company, size, role, number_of_hosts, visability)。所以在调用MyClass#new 方法时应该传递6 参数。但实际上你只通过了一个"environment"。因此,您得到了合法错误 - 参数数量错误(1 比 6)

【讨论】:

  • 是的,rspec 就是这么说的……请解释一下为什么他得到了错误(提示,有一条评论已经说过)
  • @BenjaminGruenbaum 评论不是一个答案,它是一个提示......对吧?我认为我的回答适合这篇文章.. 但不知道为什么这么多反对票..
  • 嗯,还不能取消否决票,我读到的只是第一句话。 :(
  • @ArupRakshit:另一方面,您不应该仅仅为了获得第一个答案而发布带有拼写错误的半生不熟(甚至更少)的答案。也许这解释了一些反对意见。我也喜欢成为第一个回答者,但我努力在修订版 0 中发布可用的答案。
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 2015-02-07
  • 2017-04-08
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多