【问题标题】:Rspec fields in context scope上下文范围内的 Rspec 字段
【发布时间】:2012-09-23 10:32:39
【问题描述】:

确实不知道如何表达标题,但我的问题如下:

shared_examples "something" do 
  context "for something" do 
    fields.each do |field| 
      it "should have #{field} field" do 
        #Check something 
      end
    end
  end
end

describe Clazz do
  it_behaves_like "something" do
    let(:fields) {%w{something something2}}
  end
end

由于变量是在it 范围中引入的,而不是在context 中,因此当然会在fields.each 部分执行失败。

所以我的问题是如何将带有 it_behaves_like 的变量引入上下文范围?或者我应该使用其他东西。

【问题讨论】:

    标签: ruby rspec ruby-1.9


    【解决方案1】:

    不知道shared_examples,但如果您使用shared_examples_for,您可以将参数传递给块,如下所示:

    shared_examples_for "something" do |fields|
      context "for something" do
        fields.each do |field| 
          it "should have #{field} field" do 
            #Check something 
          end
        end
      end
    end
    
    describe Clazz do
      it_behaves_like "something", %w{something something2}
    end
    

    【讨论】:

      【解决方案2】:

      shared_examples 已经创建了一个新的上下文,所以我认为最干净的方法是没有额外上下文的 shioyama 的示例:

      shared_examples_for "something" do |fields|
        fields.each do |field| 
          it "should have #{field} field" do 
            # specify something
          end
        end
      end
      
      describe Clazz do
        it_behaves_like "something", %w{something something2}
      end
      

      【讨论】:

        【解决方案3】:

        据我所知,Let 在每个 it 块之前进行评估,但不适用于 contextdescribe

        describe "something" do 
          let(:fields) { %w{something something2} }
        
          it "should have all fields" do 
            fields.each do |field| 
            end
          end
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-05-23
          • 1970-01-01
          • 1970-01-01
          • 2015-08-15
          • 2016-08-13
          • 1970-01-01
          • 2016-06-05
          相关资源
          最近更新 更多