[rspec-users] using @variables in an 'it' block

Ben Mabey ben at benmabey.com
Thu Sep 27 11:40:09 EDT 2007

Have you tried just turning @selenium into a method for lazy 
initialization?  So, you could have:

def selenium
    @selenium ||= SeleniumHelper.selenium  

The in your spec just use the method call as opposed to the instance 

That is probably what I would do.  I have never used initialize in a 
module so I don't have any ideas along those lines.


Korny Sietsma wrote:
> Hi folks,
> I'm somewhat new to the current RSpec release - at work we are still
> using 0.8.something, with "context 'blah' do ... specify 'should
> thing' ..."
> We have some helper code to automatically mix-in selenium:
> module SeleniumHelper
>   include SpecHelper
> ...
>   def initialize(arg)
>     @selenium = SeleniumHelper.selenium
>   end
> (selenium.rb also adds some method-missing magic so we don't need to
> say '@selenium.open(foo)' we can just say 'open(foo)', but that's not
> particularly relevant to my question)
> My problem is, at home in rspec 1.0.8, including this module doesn't work:
> describe ThingController do
>   include SeleniumHelper
>   it "should list all known things" do
>     @selenium.open "/thing/list"          #   ==> fails with "nil.open" error
>     SeleniumHelper.selenium.open "/thing/list"  #  ==> succeeds!
>     open "/thing/list"   # ==>fails with "nil.open" error
>   end
> end
> The first line fails - @selenium seems to be nil, I get an exception.
> The second line passes.
> The third line fails also, for the same reason as the first.
> Any thoughts?  Any hints on getting @selenium initialised?  It seems
> that the method-missing magic is (probably) working, as the third line
> fails in the same way as the first line - but I'd like to know how to
> get @selenium to exist.
> (addendum - if I add to my startup code:
>   config.before(:all) { @selenium = SeleniumHelper.selenium }
>   it seems to work! But I'm still interested in why it doesn't get set
> in "initialize"...)
> - Korny

More information about the rspec-users mailing list