Ruby & Rails

rspec let vs let!

2019-02-15  本文已影响0人  云莉6

let vs let! 只有一处不同,let 是懒加载,也就是第一次调用之后,才会被创建。let! 是不管有没有被调用,强制先创建。也就是之前我记得 java 中有一个懒汉式和饿汉式的区别。ps: 不管是 let 还是 let! 每个 it 代码块之间都是独立的干净的。

下面这个 test 可以比较完整的看出区别:

RSpec.describe "LetVsLet!" do
  before do
    Timecop.return
    Timecop.travel(Time.now)
  end
  
  describe "let" do
    let(:current_time) { Time.now.to_i }

    before { puts Time.now.to_i }

    it "gets the same time over and over again" do
      sleep(1)
      puts current_time.to_i
      sleep(1)
      puts current_time.to_i
    end

    it "gets the time again" do
      sleep(1)
      puts current_time.to_i
      sleep(1)
      puts current_time.to_i
    end
  end

  describe "let!" do
    let!(:current_time) { Time.now }

    before {
      puts Time.now.to_i
    }

    it "gets the same time over and over again" do
      sleep(1)
      puts current_time.to_i
      sleep(1)
      puts current_time.to_i
    end

    it "gets the time again" do
      sleep(1)
      puts current_time.to_i
      sleep(1)
      puts current_time.to_i
    end
  end
end

执行结果:

➜  otcbtc git:(t36818) ✗ bundle exec spring rspec spec/models/test_spec.rb:1
Running via Spring preloader in process 19966
Run options: include {:locations=>{"./spec/models/test_spec.rb"=>[1]}}

LetVsLet!
  let
1550218652
1550218653
1550218653
    gets the same time over and over again
1550218654
1550218655
1550218655
    gets the time again
  let!
1550218656
1550218656
1550218656
    gets the same time over and over again
1550218658
1550218658
1550218658
    gets the time again

Finished in 8.85 seconds (files took 0.61873 seconds to load)
4 examples, 0 failures
上一篇 下一篇

猜你喜欢

热点阅读