LoginSignup
8
7

More than 5 years have passed since last update.

[RSpec] example 内で、describe / context / it などを取得する方法

Last updated at Posted at 2017-07-27

RSpec 3.6 で確認しています。

たとえば、以下のようなサンプルを考えます。

sample_spec.rb
RSpec.describe "Movie" do
  describe "#price" do
    context "when a customer is under 18" do
      it "1000 yen" do

        # somthing
        # この中で、上の it / context / describe を取得したいと思います
      end
    end
  end
end

取得する

self.class と、RSpec.current_example から取る方法を試しています。

RSpec.describe "Movie" do
  describe "#price" do
    context "when a customer is under 18" do
      it "1000 yen" do


        p self.class.description
        #=> "when a customer is under 18"

        p self.class.superclass.description
        #=> "#price"

        p self.class.superclass.superclass.description
        #=> "Movie"


        p RSpec.current_example.metadata[:description]
        #=> "1000 yen"

        p RSpec.current_example.metadata[:example_group][:description]
        #=> "when a customer is under 18"

        p RSpec.current_example.metadata[:example_group][:parent_example_group][:description]
        #=> "#price"

        # somthing
      end
    end
  end
end

おまけ

context に正規表現を入れて、それをそのまま取得したいときがありました。その場合は、上の方法だと、/regex/.to_s となってしまいます。これだと少し面倒くさかったのですが、以下のように取ることができました。

context /(a|b)/ do
  it 'b' do
    p self.class.description
    #=> (?-mix:(a|b))"

    p RSpec.current_example.metadata[:example_group][:description]
    #=> (?-mix:(a|b))"

    p RSpec.current_example.metadata[:described_class]
    #=> /(a|b)/

    # コメントにて教えて頂いた幸せな方法!
    p described_class
    #=> /(a|b)/
  end
end

以上です。ありがとうございました。🦑

8
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7