概要
rspec helper | let
詳細
letはexample内で変数を利用したい場合に使います。
beforeで@xxxなどで変数を利用する場合との違いは、lazy loadであることです。
subject { インスタンス }
構成
$ tree ┣ lib | ┗ hige.rb ┗ spec ┣ hige_spec.rb ┗ spec_helper.rb
letはlet!で呼び出すと、beforeフック時に呼び出されます。
hige.rb
# encoding: utf-8 class Hige attr_accessor :msg def initialize(str) @str = "str" end def hige "hige-#{@str}" end end
hige_spec.rb
require 'spec_helper' require 'hige' describe Hige do subject { Hige.new("str") } $cnt = 0 $dcnt = 0 let(:cnt) {$cnt += 1} let!(:dcnt) {$dcnt += 1} it "hige1" do expect(0).to eq($cnt) expect(1).to eq($dcnt) expect(1).to eq(cnt) expect(subject.hige).to eq("hige-str") end it "hige2" do expect(1).to eq($cnt) expect(2).to eq($dcnt) expect(2).to eq(cnt) end end
テスト結果
$ rspec Run options: include {:focus=>true} All examples were filtered out; ignoring {:focus=>true} .. Finished in 0 seconds 2 examples, 0 failures