Rails FactoryBot/Rspec 没有使用 let 创建

Rails FactoryBot/Rspec not creating using let

所以这是我第一次编写单元测试,我合并了 Rspec w/FactoryBot。

我的规范在使用 @ 实例变量时工作得很好,但是当我使用 let! 时,第二个模型失败了,因为第一个模型从未创建过。

规格:

require "rails_helper"

RSpec.describe Note, :type => :model do

  before(:all) do
    let!(:event){ FactoryBot.create(:event) }
    let!(:note){ FactoryBot.create(:note) }
  end

  it "is valid with valid attributes" do
    expect(note).to be_valid
  end

end

工厂:

FactoryBot.define do
  factory :note do
    event_id Event.first.id
    content "This is a sample note"
  end
end


FactoryBot.define do
  factory :event do
    title "Event Factory Test"
    event_date Date.today
    event_time "1:30 PM"
  end
end

如您所见,注释需要事件 ID(这需要创建事件),但在尝试查找本应从 let! 中创建的 Event.first.id 时它会报错).

有什么想法吗?这 "seems" 类似于其他人在其他 rspec 测试中使用 let 的方式。

如果将

letlet! 包装在 before 块中,它们将不起作用。

require "rails_helper"
RSpec.describe Note, :type => :model do
  let!(:event){ FactoryBot.create(:event) }
  let!(:note){ FactoryBot.create(:note) }
  it "is valid with valid attributes" do
    expect(note).to be_valid
  end
end

也可以在工厂内设置关联,只需传递工厂名称即可:

FactoryBot.define do
  factory :note do
    event # short for association :event
    content "This is a sample note"
  end
end

(如厂名与协会名相同,可省略厂名)。

不过你仍然在想工厂是错误的。他们应该是生产独特的可测试记录的工厂。不是一套固定装置。您定义工厂的方式只有在创建事件后才会起作用。永远不要硬连线工厂!

如果您想稍后获取事件,请执行以下操作:

require "rails_helper"
RSpec.describe Note, :type => :model do
  let!(:note){ FactoryBot.create(:note) }
  it "has an event" do
    expect(note.event).to be_a Event
  end
end