【问题标题】:Fixing RSPEC URI::InvalidURIError: bad URI(is not URI?): error for post request test修复 RSPEC URI::InvalidURIError: bad URI(is not URI?): error for post request test
【发布时间】:2018-06-12 22:50:53
【问题描述】:

我有一个 Rails API 可以抓取网站并将网站的文本内容存储到数据库中。我正在为创建路由编写 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 自己发出帖子请求,则它是成功的。为什么 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

感谢您的洞察力!

【问题讨论】:

    标签: ruby-on-rails ruby rspec uri


    【解决方案1】:

    您在 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 
    

    【讨论】:

      【解决方案2】:

      http://www.example.com:80POST /url_contents?url=www.google.com 这是无效的网址。

      【讨论】:

      • 但是它是从哪里得到这个网址的呢?参数设置如前 { post 'POST /url_contents', params: "www.google.com" }
      • @Dog 你在哪里设置你的根 url?用户git grep 'www.example.com' 检查您设置它的位置。 url_contents?url=www.google.com此部分已附加。
      • 我想我明白了。这部分是我在 rspec 测试中设置参数的方式。我需要将其作为 url 而不是 params 传递。
      【解决方案3】:

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

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

      在编辑你的测试用例之后

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

      【讨论】:

        猜你喜欢
        • 2017-12-18
        • 1970-01-01
        • 2020-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-09
        • 2012-02-23
        • 2011-07-19
        相关资源
        最近更新 更多