2012-07-06 59 views
0

有沒有辦法給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! (:"item_#{n}") { FactoryGirl.create(:item, name: "Item-#{n}") } 

測試通過單個情況下,如果我使用:

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?

回答

0

使用回答另一個問題時,我發現瞭如何獲得的結果使用send來從字符串中獲得ruby變量。另外,我喜歡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 
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 
+0

所以我想答案是可能的,但不值得。感謝您解釋字符串與ruby可變部分。這就說得通了。我認爲你需要從''Item - '#{n}'「'中刪除單引號。早些時候,這不適合我。 – 2012-07-13 07:20:41

+0

我試過這個,它不起作用。我得到異常:'#'。 @項目是零。但是,'Item.all.each'確實可以用於我的設置。 – 2012-07-31 03:38:52