Created
March 29, 2012 23:26
-
-
Save ryanb/2244869 to your computer and use it in GitHub Desktop.
let vs def
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.
has the exact same end result as
As for when it is evaluated, the object isn't instantiated until you call
user
unless you use thelet!
form, which is evaluated immediately upon entering every test within thedescribe
orcontext
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. :-)