不同rspec上下文中的代码重用

不同rspec上下文中的代码重用,rspec,code-reuse,Rspec,Code Reuse,我正在尝试重用rails控制器规范中的一些常见代码。对于管理员用户和普通用户,我有不同的上下文。但是,对于特定的操作,大多数行为都是相同的,因此我尝试将常见的行为拉入助手函数: describe SomeController do def common_get_new # common stuff end context "regular users" do describe "GET new" do common

我正在尝试重用rails控制器规范中的一些常见代码。对于管理员用户和普通用户,我有不同的上下文。但是,对于特定的操作,大多数行为都是相同的,因此我尝试将常见的行为拉入助手函数:

describe SomeController do
    def common_get_new
       # common stuff
    end 

    context "regular users" do
        describe "GET new" do
            common_get_new
        end
    end

    context "admin users" do
        describe "GET new" do
            common_get_new
        end
    end
end
这给了我一个错误:

未定义的局部变量或方法“common\u get\u new”


我做错了什么?

尝试重新安排您的上下文,以便更深的上下文可以共享相同的设置代码:

describe SomeController do
  describe "GET new" do
    before do
       # common stuff
    end

    context "regular users" do
    end

    context "admin users" do
    end
  end
end
你试过使用吗


根据问题中的
常用方法中的内容,为了简单地消除错误,您可以将该方法放入spec/support/utilities.rb,或者按照@Chris Heald的建议去做,并在文件顶部定义方法。

我的问题是,我要分解的东西并不是真正的设置工作。规范的特定部分在不同的上下文中是相同的,我希望重用这些部分,而不是复制和粘贴。有什么方法可以做到这一点吗?在文件的顶层定义你的方法,而不是在
descripe
context
块中。什么是常见的\u获取\u新设置内容、调用should、整个示例、其他内容?@FrederickCheung它不包含设置内容。它有几个完整的例子。感谢spec/support/utilities.rb上的提示!如果有人在寻找将参数传递到共享示例中的方法:
Shared\u examples\u for“common\u perf\u test”do | name,message |
将“{name}”放入
,然后按如下方式调用共享示例:
它的行为应该像“common\u perf\u test”、“{description}”、message
describe SomeController do
  shared_examples_for "common_get_new" do
    # common stuff
  end 

  context "regular users" do
    describe "GET new" do
      it_should_behave_like "common_get_new"
    end
  end

  context "admin users" do
    describe "GET new" do
      it_should_behave_like "common_get_new"
    end
  end
end