I have a Rails API that scrapes a website and stores the site's text content to the db. I'm writing an rspec test for the create route, but I keep getting the error:
Failure/Error: before { post 'POST /url_contents?url=www.google.com' }
URI::InvalidURIError:
bad URI(is not URI?): http://www.example.com:80POST /url_contents?url=www.google.com
However, if I make the post request myself through Postman with the supplied URL, it is successful. Why is rspec giving me this URI error and how can I fix it?
This is how the test is written:
describe 'POST /url_contents' do
context 'when the url is valid' do
before { post 'POST /url_contents', params: "www.google.com" }
it 'returns a status code of 201' do
expect(response).to have_http_status(201)
end
end
end
The controller action looks like:
def create
scrapedContent = UrlContent.parser(url_params)
if scrapedContent == 403
render json: { messsage: "Invalid URL" }
else
newContent = UrlContent.new
binding.pry
newContent.content = scrapedContent.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
if newContent.save?
render json: {message: "Successfully added the url content"}, status: 201
else
render json: { message: "error, #{newContent.errors.full_messages}"}, status: 412
end
end
end
Thank you for your insight!
You are making the request in your RSpec the wrong way:
context 'when the url is valid' do
# Change this line below
before { post :create, url: "www.google.com" }
it 'returns a status code of 201' do
expect(response).to have_http_status(201)
end
end