ruby-on-rails – 需要在rspec中循环遍历数组,测试没有运行
发布时间:2020-12-17 04:01:08 所属栏目:百科 来源:网络整理
导读:我有一个测试,需要循环遍历数组中的5个元素,然后验证所有元素是否显示为页面上的列表项.我有下面的代码,这是评论’#get the first 5 blog posts’的最后一次测试.当我运行测试时,没有看到此测试,因为只有4个测试正在执行.如果我在数组代码博客之外移动’it {
我有一个测试,需要循环遍历数组中的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首先读取示例spec文件.因此,在运行任何测试之前,它会点击Blog.all.这也意味着没有数据库的人口.因此,除非先前的测试运行剩余状态,否则Blog.all将返回[].
尝试在之前创建对象将无法在您的问题中编写测试的方式.同样,这是由于Blog.all在解析时执行,而之前是在测试时执行. 为了实现你想要的,你可能需要打破“仅测试一件事”规则并将Blog.all嵌套在它的块中: 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',href: blog_path(blog.id)) end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |