因此,我在使某些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)。到eq(5)甚至通过了!
在这里非常感谢您的帮助!
答案 0 :(得分:1)
'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