2013-09-21 26 views
0

我正在尝试使用rspec为我的代码编写单元测试。我不断收到一个 “错误的参数数目” 错误:错误的参数数ruby 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的回答工作...虽然我仍然有进一步的问题:

鉴于类别:

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( “随机名称”))

任何解释?

+2

您遗漏了另外5个构造函数的参数。 –

+0

你的意思是,MyClass.new(“company”,“blah”,“blah”,“blah”,“blah”)? – fatu

+1

是啊,类似的东西 –

回答

4

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

+0

是的,这就是rspec说...心灵解释_why_他得到了错误(提示,有一个评论,已经说了) –

+0

@BenjaminGruenbaum评论不是一个答案,它的一个提示..对吗?我认为我的回答适合这个职位..但不知道为什么这么多的反对票.. –

+0

那你怎么编辑它呢? –

相关问题