零猴子补丁模式
使用 `disable_monkey_patching!` 配置选项禁用 RSpec 执行的所有猴子补丁
- 停止在全局范围内公开 DSL
- 禁用 `should` 和 `should_not` 语法,用于 rspec-expectations
- 禁用 `stub`、`should_receive` 和 `should_not_receive` 语法,用于 rspec-mocks
RSpec.configure { |c| c.disable_monkey_patching! }
背景
给定一个名为“spec/example_describe_spec.rb”的文件,其中包含
require 'spec_helper'
describe "specs here" do
it "passes" do
end
end
给定一个名为“spec/example_should_spec.rb”的文件,其中包含
require 'spec_helper'
RSpec.describe "another specs here" do
it "passes with monkey patched expectations" do
x = 25
x.should eq 25
x.should_not be > 30
end
it "passes with monkey patched mocks" do
x = double("thing")
x.stub(:hello => [:world])
x.should_receive(:count).and_return(4)
x.should_not_receive(:all)
(x.hello * x.count).should eq([:world, :world, :world, :world])
end
end
给定一个名为“spec/example_expect_spec.rb”的文件,其中包含
require 'spec_helper'
RSpec.describe "specs here too" do
it "passes in zero monkey patching mode" do
x = double("thing")
allow(x).to receive(:hello).and_return([:world])
expect(x).to receive(:count).and_return(4)
expect(x).not_to receive(:all)
expect(x.hello * x.count).to eq([:world, :world, :world, :world])
end
it "passes in zero monkey patching mode" do
x = 25
expect(x).to eq(25)
expect(x).not_to be > 30
end
end
默认情况下,RSpec 允许猴子补丁
给定一个名为“spec/spec_helper.rb”的文件,其中包含
# Empty spec_helper
当我运行 `rspec` 时
那么所有示例都应该通过。
使用 `disable_monkey_patching!` 后,猴子补丁方法将被取消定义
给定一个名为“spec/spec_helper.rb”的文件,其中包含
RSpec.configure do |config|
config.disable_monkey_patching!
end
当我运行 `rspec spec/example_should_spec.rb` 时
那么输出应该包含 %R{undefined method (`|‘)should’}
并且输出应该包含“unexpected message :stub”
当我运行 `rspec spec/example_describe_spec.rb` 时
那么输出应该包含 %R{undefined method (`|‘)describe’}。
使用猴子补丁时,`allow` 和 `expect` 语法有效
给定一个名为“spec/spec_helper.rb”的文件,其中包含
# Empty spec_helper
当我运行 `rspec spec/example_expect_spec.rb` 时
那么所有示例都应该通过。
不使用猴子补丁时,`allow` 和 `expect` 语法有效
给定一个名为“spec/spec_helper.rb”的文件,其中包含
RSpec.configure do |config|
config.disable_monkey_patching!
end
当我运行 `rspec spec/example_expect_spec.rb` 时
那么所有示例都应该通过。