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
@BrandonMathis
Copy link

I never really understood the value added by let and it's lazy evaluation. If I am going to use variables in my test then I tend to declare them outright in a before block. The attr_reader but other coders seem annoyed by that (for some reason). I like the concept of using attr_read tho. Let seems to confuse a lot of newbies who don't understand how the symbol :tasty_steak magically becomes the variable tasty_steak. Even after you grasp that concept, it is unclear as to exactly when a let is evaluated durring execution.

Readability is important in test bc it is the first place I go to understand a project. Let is useful for that. Option 2 breaks the code up too much for me and the semi-colons get in my way when scanning option 3. I like Aaron's technique of putting assignment all into that setup block.

@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