dpst
dpst

Reputation: 1283

How to not repeat writing same attributes when using `let` and `create` in nested contexts?

I have an Rspec test using FactoryBot(FactoryGirl) as follows:

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

In this test I have the initial :note with the title and body. In the nested context I want to use this same note but simply add my :many_authors trait. However, I find myself having to copy and paste the attributes title: "my test title", body: "this is the body" from the previous note so I was wondering what the best way to dry up the code would be so I wouldn't have to always copy and paste the title and body attributes. What would be the correct way to do this?

Upvotes: 0

Views: 46

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

Easy, just extract one more 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

But probably in this case setting the attributes at the factory is a better option.

Upvotes: 1

ogirginc
ogirginc

Reputation: 5270

Try giving note_factory default values

# spec/factories/note_factory.rb
FactoryGirl.define do    
  factory :note do
    title "my test title"
    body "this is the body"
  end
end

and create?

# 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

Upvotes: 0

Related Questions