使用Capybara + Rails3找不到要点击的元素

背景 :我正在使用Capybara和Rspec来测试Rails 3应用程序。 使用的驱动程序 :Selenium

问题 :我无法找到“登录”按钮,以便在我的测试中点击。

HTML代码:

测试失败

 it "should login correctly if the right credentials are given", :js => true do Capybara.default_wait_time = 5 Capybara.reset_sessions! visit '/' click_link('login_link') #this will bring a modal window with the code posted above using js within("#login") do fill_in 'user_email', :with => "my-email@example.com" fill_in 'user_password', :with => "mypwd" end response.should have_selector('input#btn_login') #This passes click_on("input#btn_login") #Here it fails, saying it can't find an element with that selector response.should have_selector(:xpath, '//div[@class="alert-message block-message info"]') end 

我的测试文件在spec/requests

有任何想法吗? 谢谢!

请试试这个:

 page.find("#btn_login").click 

这: https : //stackoverflow.com/a/11348065/1504796

是正确的答案。

click_on不采用CSS选择器,而是采用链接的文本或id。 你想要click_on("btn_login") 。 没有哈希标志或任何东西。

尝试

 find('#id',:visible => true).click 

尝试将“gem’stuny’”添加到您的Gemfile中,并在步骤文件中的失败行之前添加“save_and_open_page”行。

参考: http : //techiferous.com/2010/04/using-capybara-in-rails-3/

看起来你正试图点击某个模态css中的提交按钮。 您需要首先调用模态元素的任何显示。

我不认为click_on会采用这样的定位器 – 我认为它可能只需要一个id,名称或值。 作为实验,尝试使用以下命令替换click_on(“input#btn_login”):

page.find( ‘#btn_login’)。点击

  • click_button(“登录”)
  • find(:xpath,“//* [@ id =’btn_login’]”)。click(或.trigger(’click’))

如果else失败,请通过控制台查看是否可以检查按钮的存在:document.getElementById(“btn_login”)

如果您知道链接文本,则可以使用page.find_link(text).click 。 ( 来源 )

尝试在相关行之前添加save_and_open_page。 这应该允许您查看页面以及可能阻止单击操作的任何错误。

我使用带有铬的水豚

 Capybara.register_driver :chrome do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end Capybara.javascript_driver = :chrome 

并安装chrome驱动程序:

 brew install chromedriver 

http://collectiveidea.com/blog/archives/2011/09/27/use-chrome-with-cucumber-capybara/