1

認証されていないユーザーのリダイレクトをすばやくテストできる機能を追加しようとしています。これが私がこれまでに持っているものです:

def unauthenticated_redirects_to redirect_path #yeild
  context "when not signed in" do
    it "redirects to #{redirect_path}" do 
      yield
      expect(response).to redirect_to redirect_path
    end
  end
end


describe SomeController do
  describe 'GET #show' do 
    unauthenticated_redirects_to('/some_path') { get :show }
    context "when signed in" do
      # One thing...
      # Another thing...
    end
  end
  describe 'GET #whatever' do
    unauthenticated_redirects_to('/some_other_path') { get :whatever }
  end
end

ただし、プライマリdescribeブロックのスコープとコンテキストが に渡されたブロックで使用できないため、これは機能しませんunauthenticated_redirects_to。これは合理的にエラーにつながります: undefined method `get' for RSpec::Core::ExampleGroup::Nested_1::Nested_2:Class.

これを回避する方法はありますか、または私が検討すべき同様のことを達成するためのよりクリーンな方法はありますか?

4

4 に答える 4

0

これは、共有メタデータ (この場合) に基づいてサンプルをトリガー:auth => trueし、サンプル グループの説明を解析していくつかの重要なパラメーターを取得する、共有サンプルを使用するアプローチです。

require 'spec_helper'

class SomeController < ApplicationController
end

describe SomeController, type: :controller do
  shared_examples_for :auth => true do 
    it "redirects when not signed in" do 
      metadata = example.metadata
      description = metadata[:example_group][:description_args][0]
      redirect_path = metadata[:failure_redirect]
      http_verb = description.split[0].downcase.to_s
      controller_method = description.match(/#(.*)$/)[1]
      send(http_verb, controller_method)
      expect(response).to redirect_to redirect_path
    end
  end

  describe 'GET #show', :auth => true, :failure_redirect => '/some_path' do 
    context "when signed in" do
      # One thing...
      # Another thing...
    end
  end

  describe 'GET #whatever', :auth => true, :failure_redirect => '/some_other_path' do
  end

end
于 2013-09-05T21:45:09.693 に答える
0

完全を期すために、別の共有例アプローチを次に示します。今回beforeは、元のスコープの問題を回避する呼び出しでブロック パラメーターを使用します。

require 'spec_helper'

class SomeController < ApplicationController
end

describe SomeController, type: :controller do
  shared_examples_for 'auth ops' do 
    it "redirects when not signed in" do 
      expect(response).to redirect_to redirect_path
    end
  end

  describe 'GET #show' do
    it_behaves_like 'auth ops' do
      let(:redirect_path) {'/some_path'}
      before {get :show}
    end
    context "when signed in" do
      # One thing...
      # Another thing...
    end
  end

  describe 'GET #new' do
    it_behaves_like 'auth ops' do
      let(:redirect_path) {'/some_other_path'}
      before {get :whatever}
    end
  end
end
于 2013-09-05T22:01:26.153 に答える
0

rspec shared exampleを見てください。

于 2013-08-22T20:51:15.037 に答える