RSpec 一开始可能会让人感到困惑,因为总是有许多有效的方法可以实现相同的目标。这就是为什么我建议您获取The Rspec Book而不是(或之前)通过“许多教程和示例”。
对于这个单一的测试,我可以很容易地想出八种不同的方法(参见下面的代码示例),你可以更多地混合和匹配它们的一部分,从而产生更多不同的方法来解决相同的问题。
这就是为什么我认为在您能够通过示例和教程工作之前对 RSpec 原则有基本的了解是必要的——每个示例看起来都会略有不同,但是如果您掌握了基础知识,您将很容易能够看到每个示例的内容做。
require "rspec"
class Song
def title=(title)
@title = title
end
def title
@title.capitalize
end
end
describe Song do
before { @song = Song.new }
describe "#title" do
it "should capitalize the first letter" do
@song.title = "lucky"
@song.title.should == "Lucky"
end
end
end
describe Song do
describe "#title" do
it "should capitalize the first letter" do
song = Song.new
song.title = "lucky"
song.title.should == "Lucky"
end
end
end
describe Song do
let(:song) { Song.new }
describe "#title" do
before { song.title = "lucky" }
it "should capitalize the first letter" do
song.title.should == "Lucky"
end
end
end
describe Song do
let(:song) { Song.new }
subject { song }
before { song.title = "lucky" }
its(:title) { should == "Lucky" }
end
describe Song do
let(:song) { Song.new }
describe "#title" do
before { song.title = "lucky" }
context "capitalization of the first letter" do
subject { song.title }
it { should == "Lucky" }
end
end
end
describe Song do
context "#title" do
before { subject.title = "lucky" }
its(:title) { should == "Lucky" }
end
end
RSpec::Matchers.define :be_capitalized do
match do |actual|
actual.capitalize == actual
end
end
describe Song do
context "#title" do
before { subject.title = "lucky" }
its(:title) { should be_capitalized }
end
end
describe Song do
let(:song) { Song.new }
context "#title" do
subject { song.title }
before { song.title = "lucky" }
it { should be_capitalized }
end
end