开发者

rspec variables in different contexts/scopes

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
  end

 # 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  
   end
 end

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?


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:

http://blog.davidchelimsky.net/2010/11/07/specifying-mixins-with-shared-example-groups-in-rspec-2/


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')          
    end            
  end        
end

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜