RSpec HTTP请求测试始终通过



所以我在让一些RSpec测试失败时遇到了一些问题。无论我尝试什么,它们总是通过,好吧,其中一个测试工作正常,我验证了如果我修改它正在测试的代码,它可能会失败。

我正在尝试测试对外部API的JSON响应的内容,以确保我的控制器正确地对这些返回的JSON对象进行排序。

我是不是遗漏了什么?为什么我不能让这些失败?

RSpec.describe 'Posts', type: :request do
describe 'ping' do
it 'returns status 200' do # This text block works correctly.
get "/api/ping"
expect(response.content_type).to eq("application/json; charset=utf-8")
expect(response).to have_http_status(200)
end
end
describe 'get /api/posts' do # all tests below always pass, no matter what.
it 'should return an error json if no tag is given' do
get "/api/posts" 
expect(response.content_type).to eq("application/json; charset=utf-8")
expect(response.body).to eq("{"error":"The tag parameter is required"}")
end
it 'should return a json of posts' do
get "/api/posts?tags=tech" do
expect(body_as_json.keys).to match_array(["id", "authorid", "likes", "popularity", "reads", "tags"])
end
end
it 'should sort the posts by id, in ascending order when no sort order is specified' do
get "/api/posts?tags=tech" do
expect(JSON.parse(response.body['posts'][0]['id'].value)).to_be(1)
expect(JSON.parse(response.body['posts'][-1]['id'].value)).to_be(99)
end
end
it 'should sort the posts by id, in descending order when a descending order is specified' do
get "/api/posts?tags=tech&direction=desc" do
expect(JSON.parse(response.body['posts'][0]['id'].value)).to_be(99)
expect(JSON.parse(response.body['posts'][-1]['id'].value)).to_be(1)
end
end
end

在get块中,如果没有标记,应该返回一个错误json。do块我甚至尝试了expect(4(.to eq(5(,甚至传递了THIS!

非常感谢您的帮助!

'get'不应该有do块。这将导致测试始终通过。

所以这个:

it 'should sort the posts by id, in descending order when a descending order is specified' do
get "/api/posts?tags=tech&direction=desc" do. # <<< remove this
expect(JSON.parse(response.body['posts'][0]['id'].value)).to_be(99)
expect(JSON.parse(response.body['posts'][-1]['id'].value)).to_be(1)
end # <<< and this from all tests.
end

应该是这样的:

it 'should sort the posts by id, in descending order when a descending order is specified' do
get "/api/posts?tags=tech&direction=desc"
expect(JSON.parse(response.body['posts'][0]['id'].value)).to_be(99)
expect(JSON.parse(response.body['posts'][-1]['id'].value)).to_be(1)
end

最新更新