问题
I am having a little bit of a difficult learning curve to test a create controller action that calls an external api call with Rails, mocha, and webmock. Below is the following controller code that I want to test.
def create
@response = Cdnify.create_cdn_resource(cdn_params)
if @response.parsed_response['resources']
flash[:notice] = 'Successfully Created Resource.'
else
@response.parsed_response['errors'].each do |error|
flash[:error] = "#{error['code']}" + ': ' + "#{error['message']}"
end
end
redirect_to cdns_path(ssl_slug: @ssl_slug)
end
It's a straight forward test but I'm getting particularly confused as to how to test this code especially when it comes to mocking the external api call. I've looked at these stackoverflow questions but am still having a difficult time in regards to making webmock stub the request and then going form there to my flash messages and redirects. Here are the resources I've used:
Queston 1 answer Question 2 answer Question 3 answer
Now here is my test code:
describe 'create' do
it 'correctly creates a cdn resource, redirects to cdns#index, and shows successful flash message' do
params = {api_key: 'api_key_123456',
resource_name: 'somewebsite', resource_origin: 'http://www.somewebsite.com' }
####### Is this correct in definition and where its placed in the code? #######
####### Do I have to use webmock to create by hand the response from vcr gem? #######
Cdnify.expects(:create_cdn_resource).with(params)
###### Am I suppose to execute this? #######
post :create, params: params
assert flash[:notice]
end
end
I've peppered my questions in that little piece of code but I'm confused as to how the flow of the code should go? Am I mocking the Cdnify
class method first and then call post? Do I even need to use post
call in the code? When I do execute the post
code, vcr doesn't know how to handle the request, so am I supposed to hand craft a response
? And where does that go?
Basically, I could use some help on how to create this very basic test. I have a feeling that it should be simple, but I'm having a hard time trying to combine all this new information correctly and some help would be appreciated. Thanks.
来源:https://stackoverflow.com/questions/58862193/what-is-the-proper-way-of-mocking-my-controller-create-action-that-includes-an