2

我正在使用 gem 并想向它添加 40 多个额外的 rspec 测试。gem 带有一组规范,但它们不是很干——我想添加的 40 多个测试中的每一个都需要 10-12 行代码(每一个都非常相似)。

下面是一个测试示例,但我创建了一个要点来保存更多代码。在此处粘贴更多内容似乎不切实际。

这是要点:https ://gist.github.com/2400225

我想要做的是在一个源文件中包含 40-45 个这样的测试,这个源文件尽可能干燥。

shared_examples_for "Firefox browser" do
  it "should return 'Firefox' as its browser" do
    @useragent.browser.should == "Firefox"
  end

  it "should return :strong as its security" do
    @useragent.security.should == :strong
  end

  it { @useragent.should_not be_webkit }
end

# (repeating code would start here. I want 40-50 of these blocks.)
describe 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8' do
  before do
    @useragent = UserAgent.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8')
  end

  it_should_behave_like "Firefox browser"

  it "should return '4.0b8' as its version" do
    @useragent.version.should == "4.0b8"
  end

  it "should return '20100101' as its gecko version" do
    @useragent.gecko.version.should == "20100101"
  end

  it "should return 'Macintosh' as its platform" do
    @useragent.platform.should == "Macintosh"
  end

  it "should return 'Intel Mac OS X 10.6' as its os" do
    @useragent.os.should == "Intel Mac OS X 10.6"
  end

  it "should return nil as its localization" do
    @useragent.localization.should be_nil
  end

  it { @useragent.should_not be_mobile }
end
4

1 回答 1

3

这只是红宝石!

你可以在这里做任何你可以用 ruby​​ 做的事情。尝试这样的事情:

BROWSERS = [
    [
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8',
        'Firefox browser',
        '4.0b8',
        '20100101',
        'Macintosh',
        'Intel Mac OS X 10.6',
        nil,
        false
    ],
    # more entries
]

BROWSERS.each do |desc|
    agent_string,behave_as,version,gecko_version,platform,os,localization,mobile = *desc
    describe agent_string do
      before do
        @useragent = UserAgent.parse(agent_string)
      end

      it_should_behave_like behave_as

      it "should return '#{version}' as its version" do
        @useragent.version.should == version
      end

      it "should return '#{gecko_version}' as its gecko version" do
        @useragent.gecko.version.should == gecko_version
      end
      # etc!
      end
end
于 2012-04-16T19:33:08.507 回答