17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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
17
17
3

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
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?