Reputation: 4119
Is there a way to add a sequence to the let variable name? Sort of like this:
5.times do |n|
let (:"item_'#{n}'") { FactoryGirl.create(:item, name: "Item-'#{n}'") }
end
Then a test like this could work:
5.times do |n|
it { should have_link("Item-'#{n}'", href: item_path("item_'#{n}'") }
end
It'll lead to a test for proper sorting, but just trying to understand the basics.
Edit: There was a typo, I removed the single quotes and the let call seems to be working
let! (:"item_#{n}") { FactoryGirl.create(:item, name: "Item-#{n}") }
The test passes for a single case if I use:
it { should have_link("Item-0", href: item_path(item_0)
But not for the sequence if I use:
it { should have_link("Item-#{n}", href: item_path("item_#{n}")
I have verified the problem is in the href path. How do you interpolate item_n when the used in a path?
Upvotes: 1
Views: 1532
Reputation: 4119
Using an answer to another question, I found out how to get the result of a ruby variable from a string, using send
. Also, I do like Erez's answer because I would like to use let variables because of the lazy evaluation. Here is what I got working:
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
Upvotes: 1
Reputation: 15788
That happens because in it { should have_link("Item-#{n}", href: item_path("item_#{n}")
the href value is not a string but a ruby variable.
What I would do in your case is:
before do
@items = []
5.times do |n|
@items << FactoryGirl.create(:item, name: "Item-#{n}")
end
end
And in the spec itself:
@items.each do |item|
it { should have_link(item.name, href: item_path(item)) }
end
Upvotes: 0