I am new to VCR vcr gem and testing it in a rails application. The problem that I am facing is that I am unable to my flash messages and redirects using VCR and I am not sure how to get around it. Here is my controller action I am trying to create.
def create
@response = HTTParty.post('https://reseller.cdnify.com/api/v1/resources',
{basic_auth: { username: cdn_params[:api_key], password: 'x'}, body: { alias: cdn_params[:resource_name], origin: cdn_params[:resource_origin]}})
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
I have these following tests in my controller_test.rb
file:
describe 'create' do
let(:cdn_resource) do
HTTParty.post('https://reseller.cdnify.com/api/v1/resources', {
basic_auth: { username: 'api_key', password: 'x'},
body: { alias: 'somewebsite', origin: 'http://www.somewebsite.com' }
})
end
it "returns a succesful response for cdnify request" do
VCR.use_cassette('cdnify_valid_result_for_cdn') do
response = HTTParty.post('https://reseller.cdnify.com/api/v1/resources', {
basic_auth: { username: 'api_key', password: 'x'},
body: { alias: 'mywebsite', origin: 'http://www.mywebsite.com' }
})
assert_not_nil response.parsed_response['resources']
assert_nil response.parsed_response['errors']
end
end
it 'returns an error with an invalid cdnify request' do
VCR.use_cassette('cdnify_invalid_result_for_cdn') do
response = cdn_resource
assert_not_nil response.parsed_response['errors']
assert_nil response.parsed_response['resources']
end
end
end
Basically, I am testing a good and bad response. These tests pass but the problem that I am getting is that I can't test my redirects nor my flash messages. I've tried placing them in the VCR
do block and outside of the block but I am not able to get my tests pass. They seem to be missing. What am I doing wrong? Furthermore, my simplecov
coverage is saying that I am not executing any of the code in the create
method. Why is this the case?
As mentioned by mrzasa, I separated the service into a services folder but now I'm just missing one small crucial step in the testing process. Am I to mock the http response with mocha or can I just simply use the cassette generated to do so?
describe 'create' do
it 'correctly creates a cdn resource, redirects to cdns#index, and shows successful flash message' do
post :create, params: {api_key: 'random_api_key_12345678',
resource_name: 'somewebsite',
resource_origin: 'http://www.somewebsite.com' }
############ mocking here? #############
Do I use mocha to construct the actual response hash?
####################################################
assert flash[:notice]
end
end