你会怎么测试这个?我想在不同的条件下多次测试一组规格

时间:2011-11-07 17:47:34

标签: ruby ruby-on-rails-3 rspec tdd

我有一套使用RSpec2和Capybara编写的请求规范。这是一个例子:

  require 'spec_helper'
  describe "Product Display and Interactions" do

  it "should hide the price and show SOLD OUT in the product listing when appropriate" do
    @product = Factory.create(:sold_out_product)
    @product.sale = @sale
    @product.save!
    visit(sale_path(@sale))
    @product.sold_out?.should eq(true)
    find("#product_#{@product.id}").should have_content('Sold Out')
  end

  [...]

  end

问题是我有几个不同的销售视图模板,每个模板都有自己的产品视图部分。是否有一种干净简便的方法来指示RSpec每次运行一系列具有不同条件的规格?在这种情况下,我想在@sale记录上设置一个属性,然后再次运行所有规范。

或者可能有更好的方法来测试这种情况?我是RSpec的新手,实际上是Rails的新手。

1 个答案:

答案 0 :(得分:1)

有更好的方法来测试这个,但是,目前,如果你是新手,我建议你习惯测试和轨道,而不要混淆问题。

您可以针对当前情况执行以下操作。这将为@ sale#attribute_to_alter

的每个变体创建一个单独的示例
require 'spec_helper'
describe "Product Display and Interactions" do

    ["attr_value_1", "attr_value_2"].each do |sale_attr_value|
      it "should hide the price and show SOLD OUT in the product listing when sale attribute is set to #{sale_attr_value}" do
        @product = Factory.create(:sold_out_product)
        @sale.attribute_to_alter = sale_attr_value
        @product.sale = @sale
        @product.save!
        visit(sale_path(@sale))
        @product.sold_out?.should eq(true)
        find("#product_#{@product.id}").should have_content('Sold Out')
      end
    end

  [...]

end