33

私のページには のようなリンクが含まれている必要があります<a href="/desired_path/1">Click to go</a>

assert_select を使用してそれをどのようにテストしますか? aでタグの有無を確認したいhref="/desired_path/1"。タグの属性をどのようにテストしますか?

assert_select の使用方法を説明するリソースはありますか? ガイドと API ドキュメントを読みましたが、わかりませんでした。これを行うための推奨されるより良い方法はありますか?

私は Rails 3 で作業しており、組み込みのテスト フレームワークを使用しています。

ありがとう。

4

6 に答える 6

33

assert_select では、属性値に疑問符を使用し、その後に一致する文字列を続けることもできます。

assert_select "a[href=?]", "/desired_path/1"

特に部分的な文字列または正規表現パターンに一致させたい場合は、より使いやすい assert_select を使用する別の方法があります。

assert_select "a", :href => /acebook\.com\/share/

于 2012-06-28T18:23:04.790 に答える
21

を使用して、リンクに関する多くのことをアサートする方法を次に示しますassert_select。2 番目の引数は、href 属性をテストするための String または Regexp のいずれかです。

  # URL string (2nd arg) is compared to the href attribute thanks to the '?' in
  # CSS selector string. Also asserts that there is only one link matching
  # the arguments (:count option) and that the link has the text
  # 'Your Dashboard' (:text option)
  assert_select '.menu a[href=?]', 'http://test.host/dashboard',
      { :count => 1, :text => 'Your Dashboard' }

  # Regular expression (2nd arg) tests the href attribute thanks to the '?' in
  # the CSS selector string.
  assert_select '.menu a[href=?]', /\Ahttp:\/\/test.host\/dashboard\z/,
      { :count => 1, :text => 'Your Dashboard' }

を使用できるその他の方法についてassert_selectは、Rails actionpack 3.2.15 ドキュメントから抜粋した例を次に示します (ファイルを参照actionpack-3.2.15/lib/action_dispatch/testing/assertions/selector.rb)。

  # At least one form element
  assert_select "form"

  # Form element includes four input fields
  assert_select "form input", 4

  # Page title is "Welcome"
  assert_select "title", "Welcome"

  # Page title is "Welcome" and there is only one title element
  assert_select "title", {:count => 1, :text => "Welcome"},
      "Wrong title or more than one title element"

  # Page contains no forms
  assert_select "form", false, "This page must contain no forms"

  # Test the content and style
  assert_select "body div.header ul.menu"

  # Use substitution values
  assert_select "ol>li#?", /item-\d+/

  # All input fields in the form have a name
  assert_select "form input" do
    assert_select "[name=?]", /.+/  # Not empty
  end
于 2013-11-18T16:04:36.157 に答える
20

You can pass any CSS selector to assert_select. So to test the attribute of a tag, you use [attrname=attrvalue]:

assert_select("a[href=/desired_path/1]") do |elements|
   # Here you can test that elements.count == 1 for instance, or anything else
end
于 2011-08-17T22:32:40.403 に答える
3

Rails 4.1 から導入され、Rails 4.2 にアップグレードする assert_select を使用しているすべての人向け。

4.1ではこれが機能しました:

my_url = "/my_results?search=hello"
my_text = "(My Results)"
assert_select 'a[href=?]', my_url, my_text

4.2 では、これにより次のエラーが発生しました。

構文をこれに変更したところ、うまくいきました!:

assert_select 'a[href=?]', my_url, { text: my_text }

上記のエリオットの回答は私を助けてくれました、ありがとう:)

于 2015-08-28T08:47:54.067 に答える
2
assert_select 'a' do |link|
  expect(link.attr('href').to_s).to eq expected_url
end
于 2016-08-03T09:43:43.630 に答える