1. 基本结构
RSpec.describe Order do
it "sums the prices of its line items" do
#something...
end
end
2. 紧凑结构
RSpec.describe Order do
context "with no items" do
it "behaves one way" do
# ...
end
end
context "with one item" do
it "behaves another way" do
# ...
end
end
end
3. 别名
对于顶层的 example group
来说应该用 describe 和 context,组群内可以使用 it、specify、example。
it、specify、example 是测试的基本单元,它们内部不能使用 before 语句块。before 语句块只能在 describe 和 context 内使用。
4. 共享的样例和上下文
RSpec.shared_examples "collections" do |collection_class|
it "is empty when first created" do
expect(collection_class.new).to be_empty
end
end
RSpec.describe Array do
include_examples "collections", Array
end
RSpec.describe Hash do
include_examples "collections", Hash
end
在共享样例中几乎可以声明一切,before、after 以及 around 等钩子方法,let 声明以及紧凑结构等。
类似的用法还有 shared_context 以及 include_context。
5. 元数据
rspec-core 存储了一个包含所有样例和组群的元数据 hash。可以通过如下方法从样例中获取:
it "does something" do
expect(example.metadata[:description]).to eq("does something")
end
或者:
RSpec.shared_examples "collections" do
it "is empty when first created" do
expect(described_class.new).to be_empty
end
end
RSpec.describe Array do
include_examples "collections"
end
RSpec.describe Hash do
include_examples "collections"
end
6. RSpec 命令
获取帮助:rspec --help
以文档格式输出:rspec <spec_file> --format doc
以网页格式输出:rspec <spec_file> --format html
将 rspec
命令的参数储存到 .rspec
文件中来自动调用如:echo "--format doc" >> .rspec