【问题标题】:Code reuse in different rspec contexts不同 rspec 上下文中的代码重用
【发布时间】:2012-12-27 21:38:21
【问题描述】:

我正在尝试重用 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_get_new'

我做错了什么?

【问题讨论】:

  • common_get_new 是什么 - 设置内容、调用 should、整个示例、其他内容?
  • @FrederickCheung 它不包含设置内容。它有几个完整的例子。

标签: rspec code-reuse


【解决方案1】:

您是否尝试过使用Shared Examples

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

根据您的问题中common_get_new 方法中的内容,为了简单地摆脱您的错误,您可以将该方法放在 spec/support/utilities.rb 中,或者执行正如@Chris Heald 建议的那样,并在文件顶部定义方法。

【讨论】:

  • 感谢您提供有关 spec/support/utilities.rb 的提示!
  • 如果有人正在寻找将参数传递给共享示例的方法:shared_examples_for "common_perf_test" do | name, message | puts "#{name}",然后调用共享示例如下:it_should_behave_like "common_perf_test", "#{description}", message
【解决方案2】:

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

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

    context "regular users" do
    end

    context "admin users" do
    end
  end
end

【讨论】:

  • 我的问题是我要考虑的东西并不是真正的设置工作。规范的特定部分在不同的上下文中是相同的,我想重用部分而不是复制和粘贴。有什么办法吗?
  • 在文件的顶层定义您的方法,而不是在 describecontext 块内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多