隐式定义的主题
如果示例组的第一个参数是类,则该类的实例通过subject
方法暴露给该示例组中的每个示例。
虽然以下示例演示了如何将subject
用作面向用户的概念,但我们建议您将其保留用于支持自定义匹配器和/或隐藏其在示例中的使用的扩展库。
在顶级组中暴露的subject
给定一个名为“toplevelsubject_spec.rb”的文件,其中包含
RSpec.describe Array do
it "should be empty when first created" do
expect(subject).to be_empty
end
end
当我运行rspec ./top_level_subject_spec.rb
那么这些示例应该全部通过。
嵌套组中的subject
给定一个名为“nestedsubjectspec.rb”的文件,其中包含
RSpec.describe Array do
describe "when first created" do
it "should be empty" do
expect(subject).to be_empty
end
end
end
当我运行rspec nested_subject_spec.rb
那么这些示例应该全部通过。
嵌套组中使用不同类别的subject
(最内部的获胜)
给定一个名为“nestedsubjectspec.rb”的文件,其中包含
class ArrayWithOneElement < Array
def initialize(*)
super
unshift "first element"
end
end
RSpec.describe Array do
describe ArrayWithOneElement do
context "referenced as subject" do
it "contains one element" do
expect(subject).to include("first element")
end
end
end
end
当我运行rspec nested_subject_spec.rb
那么这些示例应该全部通过。