Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing RSPEC URI::InvalidURIError: bad URI(is not URI?): error for post request test

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!

like image 288
Dog Avatar asked Nov 30 '25 00:11

Dog


1 Answers

Try this:

Before editing your test case

before { post 'POST /url_contents', params: "www.google.com" }

After editing your test case

before { post '/url_contents', params: "www.google.com" }
like image 133
Weiyan Chan Avatar answered Dec 01 '25 16:12

Weiyan Chan