I’m trying to refactor and do a cleanup exercise from this repo and this is my solution:
RSpec.describe Invitation do
# this is the helper
def create_user_and_build_invitation
team_owner = User.create
team = Team.create name: "A fine team", owner: team_owner
team_owner.update team: team
new_user = User.create(email: 'rookie@example.com')
[new_user, Invitation.new(team: team, user: new_user)]
end
# some lines below are deleted
describe "callbacks" do
describe "after_save" do
context "with valid data" do
it "invites the user" do
new_user, invitation = create_user_and_build_invitation
invitation.save
expect(new_user).to be_invited
end
end
context "with invalid data" do
it "does not save the invitation" do
new_user, invitation = create_user_and_build_invitation
invitation.team = nil
invitation.save
expect(invitation).not_to be_valid
expect(invitation).to be_new_record
end
# ...
end
end
end
describe "#event_log_statement" do
context "when the record is saved" do
it "include the name of the team" do
new_user, invitation = create_user_and_build_invitation
invitation.save
log_statement = invitation.event_log_statement
expect(log_statement).to include("A fine team")
end
# ...
end
context "when the record is not saved but valid" do
it "includes the name of the team" do
new_user, invitation = create_user_and_build_invitation
log_statement = invitation.event_log_statement
expect(log_statement).to include("A fine team")
end
# ...
end
context "when the record is not saved and not valid" do
it "includes INVALID" do
new_user, invitation = create_user_and_build_invitation
invitation.user = nil
log_statement = invitation.event_log_statement
expect(log_statement).to include("INVALID")
end
end
end
end
and I have some questions:
- Do you have any advice to improve the code above?
- Do I need to split the helper into two: one for generating the invitation and the second for generating the new_user?
- Why this cleanup can decrease test running time? I mean the helper is creating some variable and called in each test anyway so I don’t feel like this brings more performance to the test (as far as I know, and I am new to rspec and TDD)
Thanks for your time and assistance. I truly appreciate your help and insights.