13

In order to debug a factory I've inserted rescue binding.pry at the end of a problematic line:

after_create do |my_object, proxy|
  my_object.foreign_key_id = proxy.generated_attribute rescue binding.pry

Unfortunately, inside the resulting FactoryGirl::Declaration::Implicit context I can't seem to access the context like I would in "normal" code (NameError: undefined local variable or method `proxy' for #<FactoryGirl::Declaration::Implicit:0x0...>). How do I inspect and manipulate my_object and proxy within the Pry session?

The code is called as part of the background of a Cucumber feature:

Given the following my_objects exist:
| property |
| value    |

factory_girl_rails and factory_girl/step_definitions.rb are required by the support script.

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • I think that callback block takes only one argument. Anyway you could move `binding.pry` form the rescue block, put it above the second line and see what happen. – luacassus Apr 16 '12 at 13:02
  • Could you tell us what exactly you're going to achieve? – luacassus Apr 16 '12 at 13:04
  • @luacassus: The repo has an [example](https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md) with two arguments. – l0b0 Apr 16 '12 at 13:06
  • @luacassus: Putting `binding.pry` above the failing line makes no discernable difference - `my_object` still isn't available. – l0b0 Apr 16 '12 at 13:08
  • Are you sure you're using `Factory.create` instead `Factory.build` or other method? – luacassus Apr 16 '12 at 13:10
  • It should be `create` - We're using the [Cucumber helpers](https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/step_definitions.rb#L113). – l0b0 Apr 16 '12 at 13:16

1 Answers1

28

In order to allow attribute names to define attributes without having a block argument, factory_girl evaluates the definition block using instance_eval and undefines most private methods on Object, including binding. That means that when you call binding.pry above, you're not calling pry on the binding for that block; instead, you're defining a new attribute with a name of "binding" and invoking pry on the created attribute definition.

You can get around this by using Kernel.binding.pry instead.

Joe Ferris
  • 2,712
  • 19
  • 18