语法配置
RSpec-expectations 提供的主要语法基于expect
方法,该方法显式地包装对象或代码块以对其进行设置期望。
还有一种较旧的基于should
的语法,它依赖于should
被猴子补丁到系统中的每个对象。但是,这种语法有时会导致一些令人惊讶的错误,因为 RSpec 不拥有系统中的每个对象,并且不能保证它始终能一致地工作。
我们建议您使用expect
语法,除非您有特别的原因偏好should
语法。我们没有计划完全删除should
语法,但从 RSpec 3 开始,如果您没有明确启用它,将会发出弃用警告,计划在 RSpec 4 中默认禁用它(并可能将其移至外部 gem)。
如果您有一个旧的基于should
的项目,希望将其升级到expect
,请查看transpec,它可以自动为您执行转换。
背景
给定一个名为“spec/syntaxes_spec.rb”的文件,其中包含
require 'spec_helper'
RSpec.describe "using the should syntax" do
specify { 3.should eq(3) }
specify { 3.should_not eq(4) }
specify { lambda { raise "boom" }.should raise_error("boom") }
specify { lambda { }.should_not raise_error }
end
RSpec.describe "using the expect syntax" do
specify { expect(3).to eq(3) }
specify { expect(3).not_to eq(4) }
specify { expect { raise "boom" }.to raise_error("boom") }
specify { expect { }.not_to raise_error }
end
两种语法默认可用
给定一个名为“spec/spec_helper.rb”的文件,其中包含
当我运行rspec
那么示例应该全部通过
并且输出应包含“使用 rspec-expectations 的旧:should
语法中的should
,而没有明确启用语法,已弃用”。
禁用 should 语法
给定一个名为“spec/spec_helper.rb”的文件,其中包含
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
end
当我运行rspec
那么输出应包含所有这些
8 个示例,4 个失败 |
未定义的方法 `should` |
禁用 expect 语法
给定一个名为“spec/spec_helper.rb”的文件,其中包含
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.syntax = :should
end
config.mock_with :rspec do |mocks|
mocks.syntax = :should
end
end
当我运行rspec
那么输出应包含所有这些
8 个示例,4 个失败 |
未定义的方法 `expect` |
显式启用两种语法
给定一个名为“spec/spec_helper.rb”的文件,其中包含
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.syntax = [:should, :expect]
end
end
当我运行rspec
那么示例应该全部通过
并且输出不应包含“已弃用”。