概要
rspec | 暗黙のsubject
詳細
rspec実行時にExample内でsubjectを利用できます。
subjectはデフォルトではトップ階層のdescriptionのインスタンスです。
(descriptionがネストしている場合でもトップ階層のインスタンスが設定されます)
descriptionにテスト対象のクラス名が指定してあれば、そのインスタンスを取得できます。
コンストラクタに引数を渡す必要がある場合は明示的に初期化する必要がありします。
明示的に初期化する場合は下記の構文を利用します。
subject { インスタンス }
構成
$ tree ┣ lib | ┗ hoge.rb ┗ spec ┣ hoge_spec.rb ┗ spec_helper.rb
hoge.rb
# encoding: utf-8 class Hoge def hoge "hoge" end def sub_hoge "sub_hoge" end end class Hige def initialize(str) @str = "str" end def hige "hige-#{@str}" end end
hoge_spec.rb
require 'spec_helper' require 'hoge' describe Hoge do it "hoge" do puts subject.class expect(subject.send "hoge".to_sym).to eq("hoge") end it "sub_hoge" do puts subject.class expect(subject.send "sub_hoge".to_sym).to eq("sub_hoge") end end describe Hige do subject { Hige.new("str") } it "hige" do puts subject.class expect(subject.send "hige".to_sym).to eq("hige-str") end end class ExtendedHoge < Hoge end describe Hoge do describe ExtendedHoge do it "hoge" do puts subject.class expect(subject.send "hoge".to_sym).to eq("hoge") end end end
テスト結果
$ rspec Run options: include {:focus=>true} All examples were filtered out; ignoring {:focus=>true} Hoge .Hoge .Hige .Hoge . Finished in 0.002 seconds 4 examples, 0 failures