2012-07-06 40 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