【问题标题】:Dynamically generating shared examples in RSpec 2?在 RSpec 2 中动态生成共享示例?
【发布时间】:2011-05-27 12:41:24
【问题描述】:

我试图通过创建一个共享示例组来保持我的规范干燥,该组对所有管理控制器(我的项目的 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 块的上下文中可用。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec2


    【解决方案1】:

    这是一种更清洁的方法:

    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

    【讨论】:

    • 这太棒了,谢谢!没有什么比删除代码更重要了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多