[英]What should I use in place of “assigns” when using RSpec with Rails 5+?
我目前正在以請求規范的形式測試我的一個控制器的索引操作,並希望確保對象集合被傳遞。 到目前為止,我已經查閱了這篇文章以獲得指導:
it "populates an array of contacts starting with the letter" do
smith = FactoryBot.create(:contact, lastname: 'Smith')
jones = FactoryBot.create(:contact, lastname: 'Jones')
get :index, letter: 'S'
expect(assigns(:contacts)).to match_array([smith])
end
不幸的是,上面的例子會拋出這個錯誤:
NoMethodError: assigns has been extracted to a gem. To continue using it, add `gem 'rails-controller-testing'` to your Gemfile.
我很想知道在這種情況下我會使用什么來支持分配? 對於這種新方法的一個例子,我已經上下看了很多,但結果很短。
參考只需測試控制器的輸出,而不是將手指伸入內部。 最好不要使用控制器規范 - 而是使用請求或功能規范。
控制器的輸出是包含標題和響應正文的響應對象。
因此,例如,如果您在請求規范中測試 API,您可以在響應正文中測試解析的 json:
it "returns an array of contacts starting with the letter" do
smith = FactoryBot.create(:contact, lastname: 'Smith')
jones = FactoryBot.create(:contact, lastname: 'Jones')
get :index, letter: 'S'
last_names = parsed_response["contacts"].map { |c| c["lastname"] }
expect(last_names).to include 'Smith'
expect(last_names).to_not include 'Jones'
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.