Closed jackjennings closed 7 years ago
To note: It would be helpful if this might also assert that a certain class of form was actually submitted, to ensure that the appropriate form is used.
Here's a potential implementation, though I don't know if the syntax is right. This also only stubs, without verifying:
class ActionDispatch::IntegrationTest
def stub_submit form_kind, record
controller = self.class.name.gsub(/Test\z/, "").constantize
form = form_kind.new record
controller.stub_any_instance :submit, form do
yield form
end
end
end
class ValidForm < SimpleDelegator
def valid?
true
end
end
class InvalidForm < SimpleDelegator
def valid?
false
end
end
Which leads to the syntax in the test:
test "should create client" do
stub_submit ValidForm, @client do |form|
post admin_clients_url(as: @account), params: { client_form: { name: @client.name } }
assert_redirected_to admin_client_path(form)
end
end
test "should not create invalid client" do
stub_submit InvalidForm, @client do |form|
post admin_clients_url(as: @account), params: { client_form: { name: @client.name } }
assert_response :success
end
end
EDIT: fix missing variable assignment
I don't love the interface, but it mirrors the submit form_kind, record(, params)
syntax (without the params).
This also falls apart if it were to also assert what kind of form is stubbed, since a reference to the form object class is never passed in.
Coming at it from the assert
angle, an alternate syntax could be:
assert_submits ClientForm do
post # ...
end
# or, optionally…
assert_submits ClientForm, stub: ValidForm.new(@client) do
post # ...
end
Is it weird to assert and stub at the same time? I just don't want to end up with a bunch of nested blocks…
Hm, yeah, I do prefer the latter approach, as it's more readable to me as to what is going on, and I don't feel like I'm tracing the path towards what's happening. From an initial search, I can't see anything about whether or not people think this is weird. Hmmm
I started working on a potential syntax for this, which I'll wrap up and post as a proposal in this issue.