문제

I'm new to RSpec and I'm just wondering how to reuse a context across several actions in a controller. Specifically, I have code like this:

describe "GET index" do
  context "when authorized" do
    ...
  end

  context "when unauthorized" do
    it "denys access"
  end
end

describe "GET show" do
  context "when authorized" do
    ...
  end

  context "when unauthorized" do
    it "denys access"
  end
end

...

And I'd like to DRY it up a bit. The unauthorized context is the same on every action, how can I reuse it?

도움이 되었습니까?

해결책

Shared examples are your friend:

Create a new file, something like spec/shared/unauthorized.rb and include it in your spec_helper then format it like this:

shared_examples_for "unauthorized" do
  context "when unauthorized" do
    it "denys access"
  end
end

Then in your specs:

include_examples "unauthorized"

Do that in each describe block and you should be golden.

다른 팁

if you use popular gem Devise, you can reuse devise mapping like this:

require "spec_helper"

describe Worksheet::CompanyController do
  login_user_admin #<= this macros on /spec/support/controller_macros.rb

  describe '#create' do
    it 'admin login and create worksheet' do
      post :create, worksheet_company: attributes_for(:"Worksheet::Company")
      expect(response.status).to eq(302)
      expect(response).to redirect_to(admin_root_path)
    end
  end

create and login admin_user spec/support/controller_macros.rb

module ControllerMacros
  def login_user_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user_admin]
      user_admin = FactoryGirl.create(:user_admin)
      user_admin.confirm!
      sign_in user_admin
    end
  end
end

on spec/spec_helper.rb:

RSpec.configure do |config|
  ...
  config.include Devise::TestHelpers, type: :controller
  config.extend ControllerMacros, type: :controller
  ...
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top