Skip to content

Instantly share code, notes, and snippets.

@r7kamura
Last active July 20, 2020 05:03
Show Gist options
  • Save r7kamura/1dc91ed5ab03fa0a1645e9f155d4887f to your computer and use it in GitHub Desktop.
Save r7kamura/1dc91ed5ab03fa0a1645e9f155d4887f to your computer and use it in GitHub Desktop.
shared_examples "foo" do
# ここで "foo" を参照したいのですが、何か方法はありませんか?
end
@r7kamura
Copy link
Author

r7kamura commented Nov 24, 2017

shared_examples "deletes user and redirects to top page path" do
  it "deletes user and redirects to top page path" do
    is_expected.to redirect_to(top_page_path)
    expect(::User.where(id: user.id)).not_to be_exists
  end
end

仮にこういうコードを書くケースがあるとして、このように二重に定義するのを防ぎたいというのが背景にある目的のひとつです。

@r7kamura
Copy link
Author

r7kamura commented Nov 24, 2017

shared_examples "foo" do
  File.foreach(__FILE__).take(__LINE__ - 1).last[/"(.+)"/, 1] #=> "foo"
end

なかなか案が出ないので、マクドナルド理論として、この方法を提案しておきます。

@r7kamura
Copy link
Author

ちなみに、現実のプロジェクトでは以下のようなコードで対処することにしました。

require "active_support/concern"

module MyApplication
  module SpecHelpers
    module SharedExample
      extend ::ActiveSupport::Concern

      module ClassMethods
        # @param [String] name
        def shared_example(name, &block)
          shared_examples name do
            it name, &block
          end
        end
      end
    end
  end
end

RSpec.configuration.include(MyApplication::SpecHelpers::SharedExample)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment