2013-09-21 28 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

那你怎麼編輯它呢? –

相關問題