2014-09-30 68 views
5

學習如何Rspec 3.我有一個關於匹配器的問題。我下面教程爲什麼代碼導致錯誤,而一個我註釋掉折舊警告通過基於Rspec的2Rspec 3 vs Rspec 2匹配器

describe Team do 

    it "has a name" do 
    #Team.new("Random name").should respond_to :name 
    expect { Team.new("Random name") }.to be(:name) 
    end 


    it "has a list of players" do 
    #Team.new("Random name").players.should be_kind_of Array 
    expect { Team.new("Random name").players }.to be_kind_of(Array) 
    end 

end 

錯誤

Failures: 

    1) Team has a name 
    Failure/Error: expect { Team.new("Random name") }.to be(:name) 
     You must pass an argument rather than a block to use the provided matcher (equal :name), or the matcher must implement `supports_block_expectations?`. 
    # ./spec/team_spec.rb:7:in `block (2 levels) in <top (required)>' 

    2) Team has a list of players 
    Failure/Error: expect { Team.new("Random name").players }.to be_kind_of(Array) 
     You must pass an argument rather than a block to use the provided matcher (be a kind of Array), or the matcher must implement `supports_block_expectations?`. 
    # ./spec/team_spec.rb:13:in `block (2 levels) in <top (required)>' 
+1

檢查這個【答案】(http://stackoverflow.com/questions/19960831/rspec-expect-vs-expect-with-block-whats-the-difference )for _why?_ – 2014-09-30 10:05:16

回答

6

你應該使用普通括號內爲這些測試:

expect(Team.new("Random name")).to eq :name 

當您使用大括號,要傳遞一個代碼塊。對於rspec3這意味着你會放一些期望這個塊的執行,而不是執行的結果,因此,例如

expect { raise 'hello' }.to raise_error 

編輯:但是

注意,該測試將失敗,因爲Team.new返回一個對象,而不是一個符號。所以它通過您可以修改您的測試:

expect(Team.new("Random name")).to respond_to :name 

# or 

expect(Team.new("Random name").name).to eq "Random name" 
+0

我收到一個錯誤。 https://gist.github.com/vezu/85661922adda6a877b48。謝謝你的解釋。 – Benjamin 2014-09-30 10:07:28

+1

@Benjamin - 我會說這是預期的,因爲'Team.new'返回一個對象,而不是一個符號。答案已更新。 – BroiSatse 2014-09-30 10:11:50