Help us understand the problem. What is going on with this article?

rspecのshared examplesでletで宣言した変数を引数でわたしたいとき

More than 3 years have passed since last update.

rspecの重複箇所を共有化しようと思ってshared examplesを使ってみたのですが、関数を使う感覚でやっていたらはまってしまったのでメモ残しときます。

shared_examples_for '許可しないユーザ' do |path|
  let(:user) { FactoryGirl.create(:forbidden_user) }

  it '401を返却' do
    get path, { user_id: user.id }
    expect(response.status).to eq 401
  end
end

RSpec.describe Example do
  describe 'GET /api/me/comments' do
    let(:path) { '/api/me/comments' }
    it_should_behave_like '許可しないユーザ', path
  end
end

これで実行しようとするとエラーが出てしまいます。

/home/vagrant/tryjob/spec/requests/api/v1/me/comments_spec.rb:50:in `block (3 levels) in <top (required)>': undefined local variable or method `path' for RSpec::ExampleGroups::Example::POSTApiV1MeExperiences::Nested:Class (NameError)

結局、letだと参照するときに見にいくので引数でわたす必要ないんですね。

shared_examples_for '許可しないユーザ' do
  let(:user) { FactoryGirl.create(:forbidden_user) }

  it '401を返却' do
    get path, { user_id: user.id }
    expect(response.status).to eq 401
  end
end

RSpec.describe Example do
  describe 'GET /api/me/comments' do
    let(:path) { '/api/me/comments' }
    it_should_behave_like '許可しないユーザ'
  end
end
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away