ruby - Globally Access Variables for All Cucumber Steps from inside Hooks -
currently loading yaml files inside cucumber hooks before- intention ensure dont code individually loading yaml files.
@all_yaml_files = dir.entries(@projectdata_path).select {|f| !file.directory? f}; @all_yaml_files.each |file_name| file_full_path = @projectdata_path + '/' + file_name instance_variable_set("@" + file_name.split('.')[0], yaml.load_file(file_full_path)) end
however code inside before cucumber hook. when instance variables loaded not available next scenario. how can make them run once , available scenarios , features - ie globally. loading everytime scenario.
before .... end
note: doing above , can directly access yaml_filename @yaml_filename variable without writing code. thats intention. same happens excel files, json files etc etc. called inside hooks.
edit: added "quick" solution
quick solution
you using class variables (@var
) now; these subject cucumber magic cleaned out after each scenario, noticed. makes them rather useful well, giving "clean slate" while allowing transfer state 1 step next.
this is ruby, can of course use global ruby variables ($var
) instead. still requires change existing code.
if want keep class variables @var
, still have them stick around, hooks save , restore them in globals, i.e.:
around |scenario, block| @var = $var begin block.call ensure $var = @var end end
you'll want make sure hook encountered enough fires before other hooks might have.
i don't use globals in language, try not use either @var
or $var
in cucumber. instead, prefer oop way... hence:
"clean" solution (poro)
i use singleton module such things:
# support/000_cucu_globals.rb class cucuglobals include singleton def initialize @somevalue = 'hello world' ... end attr_reader :somevalue end
elsewhere:
puts cucuglobals.instance.somevalue + "!"
adjust/extend/get creative, necessary. if want avoid typing much, feel free use shorter class name (like g
global). can make accessors class methods instead skip instance
in between. ruby (not cucumber) @ point, there not cucumber magic involved anymore.
hint: want load module pretty early. i'm sure there way "cleanly", opted name in such way found first, cucumber (000_...
).
Comments
Post a Comment