2017-11-18 206 views
0

我有一个Rspec的测试使用FactoryBot(FactoryGirl)如下:如何在嵌套上下文中使用`let`和`create`时不重复编写相同的属性?

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与标题和主体。在嵌套的上下文中,我想使用相同的note,但只需添加我的:many_authors特征。但是,我发现自己不得不复制和粘贴前一个注释中的属性title: "my test title", body: "this is the body",所以我想知道干掉代码的最佳方法是什么,所以我不必总是复制和粘贴标题和主体属性。什么是正确的方法来做到这一点?

回答

1

简单,只需提取一个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 

但可能在这种情况下在工厂设置属性是一个更好的选择。

0

尝试给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 
相关问题