Guest User

Untitled

a guest
May 27th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. # Call factory with the factory name and an optional method_name
  2. #
  3. # factory(:user)
  4. # factory(:expensive_product, :method_name => :product)
  5. #
  6. # Then in all of your it/specify blocks you can call upon a a super-mocked,
  7. # majorly-stubbed Factory.
  8. #
  9. # describe "Something awesome"
  10. # factory(:long_factory_name_for_user_model, :method_name => :user)
  11. #
  12. # it "should do something" do
  13. # user(:attribute => 'James').attribute.should == 'James'
  14. # end
  15. #
  16. # it "should do more than just that" do
  17. # u = user({:attribute => 'James'}, {:stub => 'a result'})
  18. # u.stub should == 'a result'
  19. # end
  20. # end
  21.  
  22. def factory(factory_name, options = {})
  23. method_name = (options[:method_name] || factory_name).to_s.to_sym
  24.  
  25. define_method(method_name) do |*args|
  26. var_name = "@#{method_name}"
  27. value = instance_variable_get(var_name)
  28. return value if value
  29.  
  30. attributes = args.shift || {}
  31. stubs = args.shift || {}
  32.  
  33. super_mock = Proc.new { |factory_name, attributes, stubs|
  34. Factory(factory_name, attributes).tap do |super_mock|
  35. super_mock.stub!(stubs)
  36. end
  37. }
  38.  
  39. instance_variable_set(var_name, super_mock.call(factory_name, attributes, stubs))
  40. end
  41. end
Add Comment
Please, Sign In to add comment