2012-12-27 29 views
5

我想在rails控制器规范中重用一些常见的代码。对于管理员用户和普通用户,我有不同的上下文。然而,许多行为是特定的行为一样,所以我尝试了拉那常见的行为变成一个辅助功能:在不同的rspec上下文中重复使用代码

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 

这给我的错误:

undefined local variable or method `common_get_new'

我在做什么错误?

+0

什么是common_get_new - 安装的东西,调用应该,整个例子,别的东西? –

+0

@FrederickCheung它不包含设置的东西。它有几个完整的例子。 – mushroom

回答

13

您是否尝试过使用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方法,以简单地摆脱你的错误,你可以把方法规格/支持/ utilities.rb,还是作为@克里斯Heald建议并在文件顶部定义方法。

+0

感谢您对spec/support/utilities.rb的建议! –

+0

如果有人正在寻找将参数传递给共享示例的方法: 'shared_examples_for“common_perf_test”do |名称,消息| ' 'puts“#{name}”',然后调用共享示例如下: 'it_should_behave_like“common_perf_test”,“#{description}”,message' –

0

尝试重新安排你的环境,使更深层次的上下文可以共享相同的设置代码:

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

    context "regular users" do 
    end 

    context "admin users" do 
    end 
    end 
end 
+1

我的问题是,我分解的东西不是真的安装工作。规范的特定部分在不同的上下文中是相同的,我想重复使用部分而不是复制和粘贴。任何方式来做到这一点? – mushroom

+0

在文件的顶层定义你的方法,而不是在'describe'或'context'块中。 –

相关问题