简体   繁体   中英

assert_select in IntegrationTest Ruby on Rails

I come from a Python and Java background with only basic knowledge to CSS, HTML, Ruby and trying to learn web development using Ruby on Rails. I'm trying to follow the tutorial on Michael Hartl . I constantly have a problem reading the correct API or even understanding what the API is doing when I do as it seems there's a lot of ways a certain method could be called and examples are not exhaustively shown there. In particular, I do not understand how to what arguments the assert_select method in Listing 7.25 is doing.

require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest

  test "invalid signup information" do
    get signup_path
    assert_no_difference 'User.count' do
      post users_path, params: { user: { name:  "",
                                         email: "user@invalid",
                                         password:              "foo",
                                         password_confirmation: "bar" } }
    end
    assert_template 'users/new'
    assert_select 'div#<CSS id for error explanation>'
    assert_select 'div.<CSS class for field with error>'
  end
  .
  .
  .
end

By referring to Online APIs , if one were to use assert_select without code blocks, we will use 2 arguments. However, there is only 1 here in each of the 2 examples, with # and . , and I'm not too familiar whether this is some Rails/Ruby/CSS syntax, the origins of the syntax seems mixed.

Can someone enlighten me what am I missing out here? I'm not too familiar when to use # and when to use . , and how we can "cut short" the number of arguments. There seems to always be a lot of play on punctuations like _ which are not shown here.

assert_select can be called several different ways , including with just a CSS selector, like the code in your question.

CSS selectors can contain # and . symbols. Here's what they mean:

  • # references an HTML element id
  • . references a CSS class

Ids must be unique within the document. So, div#error would find this exact element: <div id="error">Some error text</div> .

Classes on the other hand can be reused throughout the HTML document. So, div.error would find all elements like this: <div class="error">Some error text</div> .

Finally, for what it's worth, # and . are also used in Ruby to differentiate between class and instance methods. . denotes a class method. # denotes an instance method. But, that's not what's going on in the assert_select method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM