2017-11-18 207 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 
相關問題