3

我的规范中经常有以下代码:

  within "#user_#{@user.id}" do
    page.should have_content(@user.email)
  end

如果 Capybara 能够从给定的资源对象中确定想要的 ID,那就太好了,例如:

  within @user do
    page.should have_content(@user.email)
  end

是否有捷径可寻?可以尝试覆盖该find方法,但也许有更好的方法?

谢谢,乔什

4

3 回答 3

11

为什么不直接添加include ActionController::RecordIdentifierspec/support/(rspec/capybara) 或features/support(cucumber/capybara)?

然后您可以执行以下操作:

within "##{dom_id(user)}" do
  find('button').click
end

Rails 4 更新include ActionView::RecordIdentifier避免弃用警告(感谢@robertwbradford)

于 2013-12-14T20:33:26.487 回答
2

在辅助方法中执行此操作怎么样?

在规范/支持/中:

module YourHelper
  def user_element(user, prefix = nil)
    '#' + dom_id(user, prefix)
  end
end

RSpec.configure do |config|
  config.include YourHelper, :type => :request
  config.include ActionController::RecordIdentifier, :type => :request
end

然后你可以写:

within user_element(user) do
  page.should have_content(@user.email)
end
于 2013-04-09T07:46:05.437 回答
2

如果您添加这样的内容(spec/support/capybara_selectors.rb例如,添加到 ):

Capybara.add_selector(:active_record_object) do
  match { |value| value.is_a?(ActiveRecord::Base) }
  css {|record| 
    singleton_class.include ActionView::RecordIdentifier
    '#' + dom_id(record)
  }
end

Then you can use an even simpler and more intuitive syntax in your tests:

within user do
  find('button').click
end
于 2018-06-12T00:29:19.697 回答