Need to iterate over the array in rspec, the test does not work

I have a test that needs to iterate over 5 elements in an array, and then check that all elements are displayed as list items on the page. I have the code below, this is the last test with the comment "#get first 5 blog posts." When I run the tests, this test is not observed because only 4 tests are performed. If I translate the 'it {}' statement outside the array code blog, the test will become visible. How to properly record this test so that it can loop properly?

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 

end

+4
source share
2 answers

You cannot set your test this way because RSpec is DSL. RSpec first reads the sample specification files before running the tests. Thus, he gets into Blog.all before running any of the tests. It also means that there is no database. Therefore, if there is no remaining state in the previous test run, Blog.all will return [] .

Trying to create objects in before will not work with how the test is written in your question. Again, this is because Blog.all runs during parsing, and before runs during testing.

To achieve what you want, you will probably have to break the β€œonly one test” rule and embed Blog.all in the 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 
+8
source

important! for a wait loop to run, you must have 5 or more 5 blogs.

than

maybe it should be refactored as

  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 
+1
source

Source: https://habr.com/ru/post/1482223/


All Articles