2014-10-20 69 views
1

我只是想了解單元測試背後的基礎知識。我在一個名爲Player.rb的文件中寫了一個Player類。下面是代碼:在ruby中使用rspec進行首次單元測試

Class Player 

    attr_reader :health 
    attr_accessor :name 

def initialize(name, health=100) 
    @name = name.capitalize 
    @health = health 
end 

def blam 
    @health -= 10 
    puts "#{@name} just got blammed yo." 
end 

def w00t 
    @health += 15 
    puts "#{@name} just got w00ted." 
end 

def score 
    @health + @name.length 
end 

def name=(new_name) 
    @name = new_name.capitalize 
end 

def to_s 
    puts "I'm #{@name} with a health of #{@health} and a score of #{score}" 
end 
end 

這裏是我的spec文件:

require_relative 'Player' 

describe Player do 
    it "has a capitalized name" do 
     player = Player.new("larry", 150) 

     player.name.should == "Larry" 
    end 
end 

確實似乎對吧?我的問題是關於spec文件的語法。我明白爲什麼我需要玩家類。但是描述的是代碼段的做法是什麼?爲什麼我需要部分?所有似乎在做的是定義一個字符串的權利?

最後,當我運行從終端rspec的player_spec.rb,我得到這樣的警告:

Deprecation Warnings: 

Using `should` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from /Users/Jwan/studio_game/player_spec.rb:7:in `block (2 levels) in <top (required)>'. 

是什麼上面的警告是什麼意思?我是否必須用替換以啓用語法?如何啓用:should語法?爲什麼是:應該寫成符號?

回答

6

是的,這似乎是正確的。你可能會發現有用的一件事是使用subject,它可以讓你定義一個「主題」,在多個測試使用方法:

describe Player do 
    subject { Player.new("larry", 150) } 

    it "has a capitalized name" do 
    expect(subject.name).to eq "Larry" 
    end 
end 

這樣你就不必一遍又一遍在每一個測試 - 再定義playersubject會每次爲您自動初始化它。

describeit主要用於組織。一個大型項目最終會有數千個測試,而一個類中的更改可能會導致測試失敗,導致完全不同的應用程序部分。保持測試的組織性使其更容易找到並修復發生的錯誤。

至於你的警告,它看起來像你使用的舊指南或教程,告訴你使用「應該」的語法,但在RSpec 3中,此語法已被棄用,而需要「expect」語法。您可以看到我如何更改上面的代碼以使用「expect」語法。這裏是新語法的a good blog post(以及爲什麼舊語法不推薦使用)。

+1

相當多。另外,'it'塊定義了您可以訪問RSpec期望匹配器的上下文,因此它不是純粹用於組織。上下文和描述將更多用於組織目的 – 2014-10-20 15:44:53

2

it設置了一個實例。一個例子可以被認爲是一個包含一個或多個期望的實際測試(最佳實踐說每個例子有一個期望)。 expect方法和匹配器只存在於it塊中。設置爲letsubject的變量對於每個示例都是唯一的。

scenario是在功能(驗收)規格中使用的it的別名。

describe,contextfeature用於將實例組合在一起。這爲letsubject變量提供了可讀性和封裝性。

傳遞一個類describe還設置了一個隱含的主題:

RSpec.describe Array do 
    describe "when first created" do 
    it { is_expected.to be_empty } 
    end 
end 

的RSpec已經relativly最近經過努力消除其折舊should語法「猴子補丁」的核心Ruby類大轉變。

雖然建議使用expect爲新的項目,你can allowshould和其他猴子修補方法。