在RSpec 2中动态生成共享示例?

时间:2011-05-27 12:41:24

标签: ruby-on-rails ruby rspec rspec2

我正在尝试通过创建一个共享示例组来保持我的规范DRY,该组对所有管理控制器(我项目的Admin命名空间下的所有控制器)执行样板检查。我正在努力弄清楚如何去做,因为共享示例需要提供有关使用哪些操作和参数的信息。如果测试失败,理想情况下应该存在有意义的错误(即包括它正在测试的操作的细节)。

require 'spec_helper'

shared_examples "an admin controller" do

  before(:each) do
    @non_admin = User.make
    @admin = User.make(:admin)
  end

  context "as an admin user" do
    @actions.each do |action, params|

      specify "I should be able to access ##{action.last} via #{action.first}" do
        self.active_user = @admin
        send(action.first, action.last, params)

        response.status.should be_ok
      end

    end   
  end

  context "as a regular user" do
    @actions.each do |action, params|

      specify "I should be denied access to ##{action.last}" do
        self.active_user = @non_admin
        send(action.first, action.last, params)

        response.status.should be 403
      end

    end   
  end

end

describe Admin::UserNotesController do

  @user = User.make
  @actions = { [:get, :index]   => { :user_id => @user.id },
               [:get, :new]     => { :user_id => @user.id },
               [:post, :create] => { :user_id => @user.id } }

  it_behaves_like "an admin controller"

end

此错误的原因显而易见,@actions对共享示例组不可见。如果我使用let,则仅在示例的上下文中可用,而不是在describe块的上下文中。有什么想法吗?

1 个答案:

答案 0 :(得分:27)

这是一种更清洁的方式:

require 'spec_helper'

shared_examples "an admin controller" do |actions|
  context "as an admin user" do
    actions.each_pair do |action, verb|
      specify "I should be able to access ##{action} via #{verb}" do
        send(verb, action, :user_id => User.make(:admin).id)
        response.status.should be_ok
      end
    end   
  end

  context "as a regular user" do
    actions.each_pair do |action, verb|
      specify "I should be denied access to ##{action}" do
        send(verb, action, :user_id => User.make.id)
        response.status.should be 403
      end
    end   
  end
end

describe Admin::UserNotesController do
  it_behaves_like "an admin controller", { 
    :index  => :get,
    :new    => :get,
    :create => :post
  }
end

有关详细信息,请参阅http://relishapp.com/rspec/rspec-core/v/2-6/dir/example-groups/shared-examples