我有一个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
感谢您的见解!
答案 0 :(得分:1)
http://www.example.com:80POST /url_contents?url=www.google.com
这不是有效的网址。
答案 1 :(得分:0)
您在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 :(得分:0)
在编辑测试用例之前尝试此操作
before { post 'POST /url_contents', params: "www.google.com" }
编辑测试用例后和
before { post '/url_contents', params: "www.google.com" }