繁体   English   中英

错误数目的参数ruby rspec

[英]wrong number of arguments ruby rspec

我正在尝试使用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)>'

...

我想念什么?

编辑

塞尔吉奥帮助了...但是

塞尔吉奥的答案奏效了……尽管我还有一个问题:

给定班级:

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”))

有什么解释吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM