1

I am working with the let function in an rspec file. I wanted to use the let function to replace the use of string instance variables like I have used with @astr below.

describe "Static pages" do
  let (:str) { "Ruby on Rails Tutorial Sample App" }

 describe "Contact Page" do

it "should have title 'Contact'" do
    @astr = "Ruby on Rails Tutorial Sample App"
  visit '/static_pages/contact'
  expect(page).to have_title("#{@astr} | Contact")
end
end

...

Which becomes

it "should have title 'Contact'" do
  visit '/static_pages/contact'
  expect(page).to have_title("#{str} | Contact")
end

What is confusing me is why #{str} works and #{:str} does not - dereference a symbol -, just as we keep the '@' for #{@astr}, why is the convention not applied to the colon in symbols?

user1658296
  • 1,398
  • 2
  • 18
  • 46

1 Answers1

1

After you defining let(:str)..., str become a method.

So, when you call str in test, you are not calling a variable, but a method which returns something you defined.

Three benefit of let over instance variables in my opinion.

  1. It's more explicit.

  2. It's lazy. The method won't return unless you call it. But a variable is always defined and lives in memory. So let is more efficient.

  3. My own feeling only. str, as method, shows method color in my editor while instance variables show another. Method looks nicer and cleaner in my code.

Billy Chan
  • 24,625
  • 4
  • 52
  • 68