Rspec: let vs let!

  1. Sự khác nhau giữa let vs let!
  •  Let:
    •  Let chỉ có giá trị trong từng block it
    • Nếu trong 1 block mà gọi nhiều biến let thì nó sẽ khai báo 1 lần biến let ở lần gọi đầu tiên.
    • Có thể xem nó là: lazy evaluation
 Example:

$count = 0
RSpec.describe "let" do
  let(:count) { $count += 1 }

  it "memoizes the value" do
    expect(count).to eq(1)
    expect(count).to eq(1)
  end

  it "is not cached across examples" do
    expect(count).to eq(2)
  end
end
 Note:
                Note that let is lazy-evaluated: it is not evaluated until the first time
          the method it defines is invoked.
 
  •  Let!:
    • You can use let! to force the method's  invocation before each example.     
    • Có thể được hiểu là let! khi được gọi thì nó sẽ gọi trong block before ngầm trước, do đó nó được thực thi và cache lại trước khi đi vào block it.   
Example:
 
describe "GetTime" do
  let!(:current_time) { Time.now }

  before(:each) do
    puts Time.now # => 2018-07-19 09:57:52 +0300
  end

  it "gets the time" do
    sleep(3)
    puts current_time # => 2018-07-19 09:57:52 +0300
  end
end
------------
Use `let!` to define a memoized helper method that is called in a `before` hook  
$count = 0
RSpec.describe "let!" do
  invocation_order = []

  let!(:count) do
    invocation_order << :let!
    $count += 1
  end

  it "calls the helper method in a before hook" do
    invocation_order << :example
    expect(invocation_order).to eq([:let!, :example])
    expect(count).to eq(1)
  end
end
    2.  Khi nào sử dụng vào trường hợp nào:
        a.Let:
            - Lazy evaluation, chỉ chạy khi và chỉ khi nó được gọi đến. Nó được định nghĩa là 1 biến nhưng nó gần giống là một method hơn. 
        b. Let!:
           - Cần định nghĩa trước khi vào block it thực thi.
   3. Ngoài ra, còn có biến instance:
       - Nó được khai báo trong block before.
       - Tự động tạo khi được tham chiếu tới, với giá trị khởi tạo là nil.
       - Khi tạo trong khối before, thì việc khởi tạo đó diễn ra trong mọi khối it. Mặc dù trong khối it đó không sử dụng biến instance này.
       - Do đó nó làm tốn thời gian chạy test.
     

Comments

Popular Posts