ruby 修复RSPEC URI::InvalidURIError:错误的URI(不是URI?):后请求测试错误

cidc1ykv  于 2023-04-20  发布在  Ruby
关注(0)|答案(3)|浏览(184)

我有一个Rails API,它可以抓取网站并将网站的文本内容存储到数据库中。我正在为create route编写一个rspec测试,但我一直得到错误:

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

但是,如果我自己通过Postman使用提供的URL进行post请求,它是成功的。为什么rspec会给我这个URI错误,我如何修复它?

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

控制器操作如下所示:

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

谢谢你的洞察力!

pokxtpni

pokxtpni1#

试试这个:
在编辑测试用例之前

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

编辑测试用例后

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

blpfk2vs2#

您在RSpec中以错误的方式提出请求:

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
cngwdvgl

cngwdvgl3#

您访问的页面不存在

相关问题