Ruby on rails 为什么工厂女孩不';t生成后回滚并保存到rspec中

Ruby on rails 为什么工厂女孩不';t生成后回滚并保存到rspec中,ruby-on-rails,rspec,Ruby On Rails,Rspec,我不明白为什么我在2规范中的记录没有回滚: 我有两张桌子,县里有很多医院 require "rails_helper" RSpec.describe Hospital, type: :model, focus: true do context "created along with new hospital created" do it "should create new hospital" do @prefecture = FactoryGirl.create(

我不明白为什么我在2规范中的记录没有回滚: 我有两张桌子,县里有很多医院

require "rails_helper"

RSpec.describe Hospital, type: :model, focus: true do

context "created along with new hospital created" do

    it "should create new hospital" do
        @prefecture = FactoryGirl.create(:prefecture)
        hospital = FactoryGirl.build(:hospital, id: 10, prefecture: @prefecture)
        expect { hospital.save }.to change { Hospital.count }.by 1
    end

    it "should save" do
        @prefecture = FactoryGirl.create(:prefecture)
        hospital = FactoryGirl.build(:hospital, id: 10, prefecture: @prefecture)
        hospital.save
    end
end

end
如果我运行它将显示错误“id=10存在于db中” 谁能解释一下我错在哪里?
谢谢。

这不是工厂女孩的责任。您有两种选择:

  • 在测试中使用事务:
  • 使用测试后清洁DB的gem,例如:

通常,您的模型测试将使用transctions,而database cleaner用于集成/验收测试,这些测试无法在事务中运行,因为需要一个单独的进程(浏览器)来读取测试中创建的数据。

默认情况下,rspec不会为每个测试重置您的数据库。您需要配置它。因为您的第二次测试正在下降,已经存在一家id为10的医院

当您删除第二个测试的参数id并成功运行时,FactoryGirl将自动生成一个新的id


FactoryGirl的方法build不填充属性id,只填充其余属性。这是因为当您在build方法之后调用save时,FactoryGir将生成一个新的id,并且您的测试成功通过。

spec\u helper.rb
中,您是否有
配置.use\u transactional\u fixtures=true
,我试图使用那个命令,但它显示出错误。如果我在hospital build中删除“id:10”,那么它就通过了,但我不知道为什么。如果没有该配置,相同的数据将在所有测试中重复使用。这就是为什么您无法在第二次测试中保存id=10的另一家医院,因为您已经在第一次测试中创建了一家医院。如果您删除id=10,它当然会起作用,因为现在您有两个具有不同id的医院(没有id冲突)。添加配置时出现了什么错误?谢谢。这一行是在rails\u helper中添加的,而不是在spec\u helper:)是的,我没有注意到您在规范中需要
rails\u helper
而不是
spec\u helper
。我想知道为什么我的测试用例没有通过。正如我所知,每个测试规范都会回滚,但在我的例子中,它不是回滚。如果我在医院建筑中移除“id:10”,那么它就通过了。