ruby-on-rails - 需要循环遍历rspec中的一个数组,测试不运行

标签 ruby-on-rails ruby rspec capybara integration-testing

我有一个测试需要遍历数组中的 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 将返回 []

尝试在 before 中创建对象将无法按照您问题中编写测试的方式工作。同样,这是由于 Blog.all 在解析时执行,而 before 在测试时执行。

为了实现您想要的效果,您可能需要打破“只测试一件事”的规则并将 Blog.all 嵌套在 it block 中:

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

关于ruby-on-rails - 需要循环遍历rspec中的一个数组,测试不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16698396/

相关文章:

ruby-on-rails - 如何 stub 删除关联以返回 false

ruby-on-rails - 从字符串创建 seo 友好的 url

ruby-on-rails - 如何使 strftime 和 GROUP 以及 WHERE 在 Postgres 中工作

存储 riak 对象时 Ruby 脚本挂起

ruby - 如何读取值并将其作为参数传递给 watir 中的下一步

ruby - RSpec Rake 文件,但没有要加载的此类文件 -- rake/tasklib

ruby-on-rails - Rails 中 1 个模型的 2 个用户定义类

ruby-on-rails - Ruby/Rails - JSON.parse/JSON.decode 问题

ruby - 检查字符串是否仅包含 Ruby 中的正数

ajax - 使用 Capybara 测试在 AJAX 请求完成之前加载消息内容