3

我有一个链接如下,我正在尝试测试(请忽略方括号):

[%= link_to "删除用户", destroy_user_account_path(@profile.user), :class => "delete", :confirm => "a", :title => "Delete #{@profile.user.name}", :method => :delete %]

下面的测试失败,但如果我注释掉 :confirm => "a" 行,它会通过:

  it "should have a link to delete the user's account (using the destroy_user_account action in the registrations controller)" do
    get :show, :id => @profile
    response.should have_selector("a",
                                  :href => destroy_user_account_path(@profile.user),
                                  :confirm => "a",
                                  :title => "Delete #{@profile.user.name}",
                                  :class => "delete", 
                                  :content => "Delete User")
  end

看我的失败:(

 Failure/Error: response.should have_selector("a",
   expected following output to contain a <a title='Delete Michael Hartl' class='delete' href='/destroy-user-account/159' confirm='a'>Delete User</a> tag:

该行的实际 html 输出如下(同样,方括号是我的)。我注意到它在这里输出“数据确认”作为属性,而不是测试所期望的“确认”属性。

[a href="/destroy-user-account/159" class="delete" data-confirm="a" data-method="delete" rel="nofollow" title="删除 Michael Hartl"]删除用户[/一种]

谁能解释在这种情况下确认和数据确认之间有什么区别,并帮助我弄清楚为什么会出现此错误/如何解决?

谢谢!

4

2 回答 2

1

“确认”不是 HTML 属性。data-whatever标签是 HTML5 的一项功能,允许您在元素上放置所需的任何自定义属性,主要用于在客户端与 Javascript 之间传递信息。

所以:<a confirm="foo"></a>不是有效的 HTML,但是<a data-confirm="foo"></a>是。

Rails UJS 会查找data-confirm标签并知道在您单击它们时会提示您一条确认消息。它从data-confirm值中获取确认消息。

因此,在这种情况下,您的代码应为:

response.should have_selector("a",
                              :href => destroy_user_account_path(@profile.user),
                              'data-confirm' => "a",
                              :title => "Delete #{@profile.user.name}",
                              :class => "delete", 
                              :content => "Delete User")

那应该可以解决您的问题,如果没有,请告诉我。

于 2012-04-20T17:23:35.343 回答
1

“确认”选项只是 link_to 提供的“数据确认”的别名。

link_to anything, :confirm => "Message" # is equivalent to
link_to anything, 'data-confirm' => "Message"

但是您使用的匹配器不知道别名,因此您需要在那里使用“数据确认”:

response.should have_selector("a",
                              :href => destroy_user_account_path(@profile.user),
                              'data-confirm' => "a",
                              :title => "Delete #{@profile.user.name}",
                              :class => "delete", 
                              :content => "Delete User")
于 2012-04-20T17:33:07.397 回答