需要在rspec中循环遍历数组,测试不运行

Wal*_*ale 4 ruby integration-testing rspec ruby-on-rails capybara

我有一个测试,需要循环遍历数组中的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
Run Code Online (Sandbox Code Playgroud)

结束

Aar*_*n K 10

由于RSpec是DSL,因此无法以这种方式嵌套测试.在运行测试之前,RSpec首先读取示例spec文件.因此它会Blog.all在运行任何测试之前点击.这也意味着没有数据库的人口.因此,除非先前测试运行中的剩余状态Blog.all将返回[].

尝试在一个文件中创建对象before无论是在问题中写入测试的方式都不起作用.同样,这是由于Blog.all在解析时before执行,而在测试时执行.

为了实现你想要的,你可能需要打破"只测试一件事"规则并嵌套Blog.allit块内:

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
Run Code Online (Sandbox Code Playgroud)