如何在RSpec中重用上下文?

时间:2014-01-06 17:13:09

标签: ruby-on-rails ruby rspec dry controllers

我是RSpec的新手,我只是想知道如何在控制器中的多个动作中重用上下文。具体来说,我有这样的代码:

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

...

而且我想干一点。未经授权的上下文在每个操作上都是相同的,我该如何重用它?

2 个答案:

答案 0 :(得分:5)

共享示例是你的朋友:

创建一个新文件,例如spec/shared/unauthorized.rb,并将其包含在spec_helper中,然后将其格式化为:

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

然后在你的规格中:

include_examples "unauthorized"

在每个描述块中都这样做,你应该是金色的。

答案 1 :(得分:1)

如果你使用流行的宝石Devise,你可以像这样重用设计映射:

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

创建并登录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