【问题标题】:How would you test this? I Want to test a set of specs several times in varying conditions你将如何测试这个?我想在不同的条件下多次测试一组规格
【发布时间】:2026-01-11 21:40:01
【问题描述】:

我有一组使用 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 的新手。

【问题讨论】:

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


    【解决方案1】:

    有“更好”的方法来测试它,但是,目前,如果你是新手,我建议你习惯于测试和 rails,而不会混淆这个问题。

    您可以针对当前情况执行以下操作。这将为@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
    

    【讨论】:

      最近更新 更多