Skip to content

Instantly share code, notes, and snippets.

@ryanb
Created March 29, 2012 23:26
Show Gist options
  • Save ryanb/2244869 to your computer and use it in GitHub Desktop.
Save ryanb/2244869 to your computer and use it in GitHub Desktop.
let vs def
desc "A user's comment" do
let(:user) { User.create! name: "John" }
let(:comment) { user.comments.create! }
it "delegates to user's name" do
comment.name.should eq(user.name)
end
end
desc "A user's comment" do
def user
@user ||= User.create! name: "John"
end
def comment
@comment ||= user.comments.create!
end
it "delegates to user's name" do
comment.name.should eq(user.name)
end
end
desc "A user's comment" do
def user; @user ||= User.create! name: "John"; end
def comment; @comment ||= user.comments.create!; end
it "delegates to user's name" do
comment.name.should eq(user.name)
end
end
@jgaskins
Copy link

@KeysetTS It doesn't become a variable at all, it defines a method with that name at runtime that returns the value returned by the block given, which is then cached.

let(:user) { User.new }

has the exact same end result as

def user
  @user ||= User.new
end

As for when it is evaluated, the object isn't instantiated until you call user unless you use the let! form, which is evaluated immediately upon entering every test within the describe or context block in which that it is defined. Sure, it's a little advanced and it's a bit of an acquired taste, but the conciseness is always nice when you're writing dozens of them. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment