Take the 2-minute tour ×

I'm trying to do some things with rspec and I'm not able to access the variables I need in the places I need them. For example:

describe "some things" do
  it "should have things in App" do
    App.things.should_not be_nil #no problems here
    # puts App.things.count
    # => 10

 # puts App.things.count
 # => 0
 App.things.each do |thing|
   #this doesn't work at all as App.things is empty 
   it "#{thing.title} should have an account number" do
      thing.acc_no.should_not be_nil  

I guess this occurs because of the time the different blocks are called. Or maybe I'm missing the point completely.

I need to iterate over 'things' and make an assertion about each one, but I can't do that because things doesn't have any elements in the context of the describe block, only within the it block.

Any help?

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

It seems you're doing it wrong: why test every single value of a collection?

  • create some fixtures and test that App has the correct number of created objects

  • use one of the created fixtures to test that has correct values, that runs validations, etc...

at least, you can use rspec's shared examples to repeat common tests:


share|improve this answer
I'm testing with capybara. I need to make sure the objects in the dom have the correct state. –  user810416 Jun 22 '11 at 13:41
so use capybara's xpath and iterate over results, but that code will not work. btw, create 1 test and check inside it (for example doing a comparision between 2 arrays) –  Andrea Pavoni Jun 22 '11 at 14:08
add comment

I don't know if this helps, but I had a similar issue. The reason I wanted to iterate over an "it" block was so the rspec failure messages would contain the name of the thing i was iterating over.

In my case, it was a series of dom ids that may or may not contain a div, depending on the status of different objects on the page.

So i did:

%w{preliminary_project_proposal final_project_proposal progress_report preliminary_abstract final_abstract preliminary_presentation final_presentation}.each do |id|
  it "should not show a late message for #{id}" do
    within "##{id}" do
      page.should_not have_css('.late_assignment')          

This worked fine. As you pointed out, I could not move the array assignment to a variable or a method, which meant that it appeared in several places, which was not very pretty.

share|improve this answer
add comment

Your Answer


