在嵌套上下文中使用“let”和“create”时如何不重复编写相同的属性?
How to not repeat writing same attributes when using `let` and `create` in nested contexts?
我使用 FactoryBot(FactoryGirl) 进行了 Rspec 测试,如下所示:
describe Note do
let(:note) {create(:note, title: "my test title", body: "this is the body")}
expect(note.title).to eq "my test title"
expect(note.body).to eq "this is the body"
context "with many authors" do
let(:note) {create(:note, :many_authors, title: "my test title", body: "this is the body")}
it "has same title and body and many authors" do
expect(note.title).to eq "my test title"
expect(note.body).to eq "this is the body"
expect(note.authors.size).to eq 3
end
end
end
在这个测试中,我有标题的初始 :note
和 body。在嵌套上下文中,我想使用相同的 note
但只需添加我的 :many_authors
特征。但是,我发现自己必须复制并粘贴上一个注释中的属性 title: "my test title", body: "this is the body"
,所以我想知道干掉代码的最佳方法是什么,这样我就不必总是复制并粘贴标题和body 属性。执行此操作的正确方法是什么?
尝试给出 note_factory
默认值
# spec/factories/note_factory.rb
FactoryGirl.define do
factory :note do
title "my test title"
body "this is the body"
end
end
并创建?
# spec/models/note_spec.rb
describe Note do
let(:note) { create(:note) }
...
context "with many authors" do
let(:note) { create(:note, :many_authors) }
...
end
end
简单,再提取一个let
。
describe Note do
let(:note_creation_params) { title: "my test title", body: "this is the body" }
let(:note) { create(:note, note_creation_params) }
context "with many authors" do
let(:note) { create(:note, :many_authors, note_creation_params) }
end
end
但在这种情况下,在工厂设置属性可能是更好的选择。
我使用 FactoryBot(FactoryGirl) 进行了 Rspec 测试,如下所示:
describe Note do
let(:note) {create(:note, title: "my test title", body: "this is the body")}
expect(note.title).to eq "my test title"
expect(note.body).to eq "this is the body"
context "with many authors" do
let(:note) {create(:note, :many_authors, title: "my test title", body: "this is the body")}
it "has same title and body and many authors" do
expect(note.title).to eq "my test title"
expect(note.body).to eq "this is the body"
expect(note.authors.size).to eq 3
end
end
end
在这个测试中,我有标题的初始 :note
和 body。在嵌套上下文中,我想使用相同的 note
但只需添加我的 :many_authors
特征。但是,我发现自己必须复制并粘贴上一个注释中的属性 title: "my test title", body: "this is the body"
,所以我想知道干掉代码的最佳方法是什么,这样我就不必总是复制并粘贴标题和body 属性。执行此操作的正确方法是什么?
尝试给出 note_factory
默认值
# spec/factories/note_factory.rb
FactoryGirl.define do
factory :note do
title "my test title"
body "this is the body"
end
end
并创建?
# spec/models/note_spec.rb
describe Note do
let(:note) { create(:note) }
...
context "with many authors" do
let(:note) { create(:note, :many_authors) }
...
end
end
简单,再提取一个let
。
describe Note do
let(:note_creation_params) { title: "my test title", body: "this is the body" }
let(:note) { create(:note, note_creation_params) }
context "with many authors" do
let(:note) { create(:note, :many_authors, note_creation_params) }
end
end
但在这种情况下,在工厂设置属性可能是更好的选择。