我正在關注該書APIs on Rails。我在第8章。當使用RSpec 3.6進行測試時,我收到了以前沒有得到的錯誤。即使我在git checkout
這些測試通過的提交中,我也會收到它們。我確定他們是,因爲我正在撰寫一篇博文,關於在Rails 5.1.3中關注這本書。我發現他們沒有通過,在第8章結束時運行整個測試套件(失敗的規範來自第7章和第6章)。在我運行大多數特定文件的規格之前。失敗(先前通過)RSpec測試即使在提交後
所以我認爲這個問題可能是系統相關的,但是我是在終端的應用程序之外做的唯一的事情就是:
$ swapoff -a
$ swapon -a
,也許sudo apt-get update
所以我左右爲難現在。
該錯誤:
與此錯誤的情況是FactoryGirl
是創建產品的4個實例,而測試GET請求後得到6〜#index
動作
的products_controller_spec.rb:
require 'rails_helper'
RSpec.describe Api::V1::ProductsController, type: :controller do
...
describe "GET #index" do
before(:each) do
4.times { FactoryGirl.create :product }
end
context "when is not receiving any product_ids parameter" do
before(:each) do
get :index
end
it "returns 4 records from the database" do
products_response = json_response[:products]
expect(products_response).to have(4).items
end
...
end
...
end
...
end
錯誤消息:
Api::V1::ProductsController GET #index when is not receiving any product_ids parameter returns 4 records from the database
Failure/Error: expect(products_response).to have(4).items
expected 4 items, got 6
如果我puts products_response
失敗的測試之前,我有這六個記錄JSON:
[
{
"id": 1,
"title": "Audible Remote Amplifier",
"price": "100.0",
"published": false,
"user": {
"id": 1,
"email": "[email protected]",
"created_at": "2017-08-27T12:13:26.977Z",
"updated_at": "2017-08-27T12:13:26.977Z",
"auth_token": "KA1ugPyXzXsULh6rN6QX",
"product_ids": [
1
]
}
},
{
"id": 2,
# rest of attributes
},
{
"id": 3,
# rest of attributes
},
{
"id": 4,
# rest of attributes
}
},
{
"id": 5,
# rest of attributes
},
{
"id": 6,
# rest of attributes
}
]
測試手動:
我的應用程序似乎做工精細。同時擊中了api.mydomain.dev/products
,我得到了很好的JSON響應中rails console
創造3個產品後:
{
"products": [
{
"id": 1,
"title": "product",
"price": "3.3",
"published": false,
"user": {
"id": 1,
"email": "[email protected]",
"created_at": "2017-08-13T07:31:29.339Z",
"updated_at": "2017-08-27T13:09:06.948Z",
"auth_token": "HJLb-d4DpgxQDzkR1RDf",
"product_ids": [
1,
2
]
}
},
{
"id": 2,
# attrs of second product in json
},
{
"id": 3,
# attrs of third product in json
}
]
}
,並在網址參數一樣api.mydomain.dev/products?min_price=15&max_price=30
(其中順便說一句是兩個失敗這裏不包括規範的其餘部分):
{
"products": [
{
"id": 3,
"title": "ps two",
"price": "20.0",
"published": false,
"user": {
"id": 2,
"email": "[email protected]",
"created_at": "2017-08-27T12:50:58.905Z",
"updated_at": "2017-08-27T12:50:58.905Z",
"auth_token": "YynJJeyftTEX49KU1-qL",
"product_ids": [
3
]
}
}
]
}
我在spec/models/product_spec.rb中有4個錯誤,但爲了保持這個問題的簡短,我不會在這裏包括它們。我認爲原因是一樣的,這個錯誤是最簡潔的。
我可以提供更多的代碼,但是它在我的github倉庫中是公開的,例如, app/models/product.rb或app/api/v1/products_controller.rb
總結:
該應用程序工作正常並且提供期望的輸出,同時人工測試。即使在提交到這些測試通過的地方之後,我也會在自動測試時發現錯誤。這可能表明問題出在系統方面。如果它不在系統方面,爲什麼它在獲得四個之前獲得額外的兩個對象?哪裏有問題?
是的,就是這樣。爲了快速檢查,我按照你所說的去了'rails c test',並且這2條記錄在那裏(不知道怎麼做)。我用'Product.destroy_all'銷燬了它們,並且所有五個測試都通過了。似乎我需要挖掘DatabaseCleaner文檔。謝謝師父。 – ToTenMilan
很高興我能幫到你。乾杯。 –