From 699759ffa2d76c72b53d0726dccb5c9b5e756a90 Mon Sep 17 00:00:00 2001 From: Gregory Igelmund Date: Tue, 13 Jun 2023 10:08:54 +0200 Subject: [PATCH] DefinitionProxy#method_missing: Forward given block to #association Fixes #1503 Why: ---- When defining an association the block-argument will be ignored when also providing a `factory`-key on the association definition. This behaviour might be unexpected, so we should raise an error that the passed block is unexpected/ignored. --- lib/factory_bot/definition_proxy.rb | 2 +- spec/factory_bot/definition_proxy_spec.rb | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/factory_bot/definition_proxy.rb b/lib/factory_bot/definition_proxy.rb index dc139ad56..0907f209d 100644 --- a/lib/factory_bot/definition_proxy.rb +++ b/lib/factory_bot/definition_proxy.rb @@ -94,7 +94,7 @@ def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondTo if association_options.nil? __declare_attribute__(name, block) elsif __valid_association_options?(association_options) - association(name, association_options) + association(name, association_options, &block) else raise NoMethodError.new(<<~MSG) undefined method '#{name}' in '#{@definition.name}' factory diff --git a/spec/factory_bot/definition_proxy_spec.rb b/spec/factory_bot/definition_proxy_spec.rb index 4523cd9fa..d1dbb88a3 100644 --- a/spec/factory_bot/definition_proxy_spec.rb +++ b/spec/factory_bot/definition_proxy_spec.rb @@ -74,6 +74,19 @@ "Did you mean? 'static_attributes_are_gone { \"true\" }'\n" ) end + + it "raises an AssociationDefinitionError when called with a `:factory`-key and providing a block" do + definition = FactoryBot::Definition.new(:user) + proxy = FactoryBot::DefinitionProxy.new(definition) + invalid_call = lambda do + proxy.author(factory: :user) { :this_should_raise_an_error } + end + + expect(invalid_call).to raise_error( + FactoryBot::AssociationDefinitionError, + "Unexpected block passed to 'author' association in 'user' factory" + ) + end end describe FactoryBot::DefinitionProxy, "#sequence" do