事务性示例
默认情况下,rspec 在事务中执行每个单独的示例。
您也可以在配置属性“usetransactionalexamples”中显式启用/禁用事务。
在事务中运行(默认)
给定一个名为“spec/models/widget_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe Widget, type: :model do
it "has none to begin with" do
expect(Widget.count).to eq 0
end
it "has one after adding one" do
Widget.create
expect(Widget.count).to eq 1
end
it "has none after one was created in a previous example" do
expect(Widget.count).to eq 0
end
end
当我运行rspec spec/models/widget_spec.rb
那么示例应该全部通过。
在事务中运行(显式)
给定一个名为“spec/models/widget_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.configure do |c|
c.use_transactional_examples = true
end
RSpec.describe Widget, type: :model do
it "has none to begin with" do
expect(Widget.count).to eq 0
end
it "has one after adding one" do
Widget.create
expect(Widget.count).to eq 1
end
it "has none after one was created in a previous example" do
expect(Widget.count).to eq 0
end
end
当我运行rspec spec/models/widget_spec.rb
那么示例应该全部通过。
禁用事务(显式)
给定一个名为“spec/models/widget_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.configure do |c|
c.use_transactional_examples = false
c.order = "defined"
end
RSpec.describe Widget, type: :model do
it "has none to begin with" do
expect(Widget.count).to eq 0
end
it "has one after adding one" do
Widget.create
expect(Widget.count).to eq 1
end
it "has one after one was created in a previous example" do
expect(Widget.count).to eq 1
end
after(:all) { Widget.destroy_all }
end
当我运行rspec spec/models/widget_spec.rb
那么示例应该全部通过。
在具有夹具的事务中运行
给定一个名为“spec/models/thing_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe Thing, type: :model do
fixtures :things
it "fixture method defined" do
things(:one)
end
end
给定一个名为“spec/fixtures/things.yml”的文件,其中包含
one:
name: MyString
当我运行rspec spec/models/thing_spec.rb
那么示例应该全部通过。