1

let変数名にシーケンスを追加する方法はありますか?このようなもの:

5.times do |n|
    let (:"item_'#{n}'") { FactoryGirl.create(:item, name: "Item-'#{n}'") }
end

次に、このようなテストが機能する可能性があります。

5.times do |n|
    it { should have_link("Item-'#{n}'", href: item_path("item_'#{n}'") }
end

それは適切なソートのテストにつながりますが、基本を理解しようとしているだけです。

編集:タイプミスがありました。一重引用符を削除しましたが、let呼び出しが機能しているようです。

let! (:"item_#{n}") { FactoryGirl.create(:item, name: "Item-#{n}") }

私が使用する場合、テストは1つのケースに合格します。

it { should have_link("Item-0", href: item_path(item_0)

しかし、私が使用する場合のシーケンスではありません:

it { should have_link("Item-#{n}", href: item_path("item_#{n}")

問題がhrefパスにあることを確認しました。パスで使用される場合、item_nをどのように補間しますか?

4

2 に答える 2

1

別の質問への回答を使用して、を使用して文字列からルビー変数の結果を取得する方法を見つけましたsend。また、遅延評価のためにlet変数を使用したいので、Erezの回答が好きです。これが私が働いたものです:

describe "test" do
  5.times do |n|
    # needs to be instantiated before visiting page
    let! (:"item_#{n}") { FactoryGirl.create(:item, name: "item-#{n}") }
  end

  describe "subject" do
    before { visit items_path }

    5.times do |n|
      it { should have_link("item-#{n}", href: item_path(send("item_#{n}"))) }
    end
  end
end
于 2012-08-26T01:25:50.350 に答える
0

これはit { should have_link("Item-#{n}", href: item_path("item_#{n}")、href値が文字列ではなく、ruby変数であるために発生します。

あなたの場合、私がすることは次のとおりです。

before do
  @items = []
  5.times do |n|
    @items << FactoryGirl.create(:item, name: "Item-#{n}")
  end
end

そして仕様自体では:

@items.each do |item|
  it { should have_link(item.name, href: item_path(item)) }
end
于 2012-07-13T06:42:41.410 に答える