[英]Need to loop through an array in rspec, test not running
我有一個測試,該測試需要遍歷數組中的5個元素,然后驗證所有元素都在頁面上顯示為列表項。 我有下面的代碼,這是帶有注釋'#get the first 5 blog posts'的最后一個測試。 當我運行測試時,因為只有4個測試正在執行,所以看不到該測試。 如果我將'it {}'語句移到數組代碼博客之外,則該測試變為可見。 我該如何正確編寫此測試以使其正確循環?
require 'spec_helper'
require 'requests/shared'
describe "Header" do
let (:title) { "my title" }
subject { page }
before { visit root_path }
describe "Home" do
it { should have_selector('title', text: title) }
it { should have_selector('header') }
it { should have_link 'Home', href: root_path}
describe "Blog link exist" do
it { should have_link 'Blog'}
end
describe "Blog list elements" do
#get the first 5 blog posts
Blog.all(limit:5).each do |blog|
it { should have_selector('ul.accordmobile li#blog ul li a', text: blog.title, href: blog_path(blog.id)) }
end
end
end
結束
由於RSpec是DSL,因此您無法以這種方式嵌套測試。 在運行測試之前,RSpec首先讀取示例規范文件。 因此, Blog.all
在運行任何測試之前訪問Blog.all
。 這也意味着沒有數據庫的填充。 因此,除非先前測試運行有剩余狀態,否則Blog.all
將返回[]
。
嘗試在before
創建對象與您在問題中編寫測試的方式都不起作用。 同樣,這是由於Blog.all
在解析時執行,而before
在測試時執行。
為了實現所需的功能,您可能需要打破“僅測試一件事”規則,並將Blog.all
嵌套在it
塊中:
it "list the first five posts" do
Blog.all(limit:5).each do |blog|
expect(page).to have_selector('ul.accordmobile li#blog ul li a',
text: blog.title,
href: blog_path(blog.id))
end
end
重要! 為了希望循環運行,您應該擁有5個或超過5個博客。
比做
可能這應該重構為
Blog.limit(5).each do |blog|
it { should have_selector('ul.accordmobile li#blog ul li a', text: blog.title, href: blog_path(blog.id)) }
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.