测试 JS 加载出的元素,Capybara 抛错 Capybara::ElementNotFound

hegwin · 2013年01月30日 · 最后由 leonworld 回复于 2014年05月28日 · 3387 次阅读

背景:rspec+capybara 给一个 sinatra 的项目做测试

页面上有一段 div 元素(里面有个 input),原先是隐藏的。

<div class="control-group" id="execute-time" style="display: none">
  <label class="control-label" for="ExecuteTime">ExecuteTime</label>
  <div class="controls">
    <p><input type="text" class="input-small timepicker" name="schedule[ExecuteTime][]"> <a class="btn btn-mini add-time">Add More</a></p>
  </div>
</div>

在一个选择框选择某个选项后,上面那个 div 才会显示出来。

$("div#frequence select").change(function() {
  //大致就是当select的val() == 'daily'
 $('div#execute-time').slideDown('500')
})

自己手动在浏览器点击是好的,但是下面这个测试代码运行的时候就会出错

require_relative '../spec_helper'

describe 'Schedules' do

  before do
    page.driver.browser.basic_authorize 'name', 'password'
    visit '/'
  end

  it "should create new schedule" do
    click_link 'New Schedule'
    page.should have_selector("h1", :text => "New Schedule")
    within(:css, 'div.form') do
      # 填其他的值之类的
      select 'daily', :from => 'schedule[Frequence]'
      fill_in 'schedule[ExcuteTime][]', :with => "08:00"
    end
    click_button 'Create'
    # .....
  end

end

出错的信息是这样的

Capybara::ElementNotFound:
cannot fill in, no text field, text area or password field with id, name, or label 'schedule[ExcuteTime][]' found

我尝试去 p page.html,结果发现那个 div 的 style 依然是display: none

嗯,这边是 rspec_helper.rb 的代码。

ENV["RACK_ENV"] = "test"

require_relative "../config/boot.rb"
require 'rspec'
require 'capybara'
require 'capybara/dsl'

Capybara.app = Sinatra::Application

RSpec.configure do |config|
  config.include Capybara::DSL

  config.before do
    FileUtils.rm LOCK_FILE if File.exist? LOCK_FILE
  end
end

另外,我尝试去给 decribe 加了个 :js => true,然后 在 spec_helper.rb 里写上require 'capybara/rspec',结果是会报另个错误:

NoMethodError:
undefined method `authorize' for #<Selenium::WebDriver::Driver:0x1c270508 browser=:firefox>

我把authorize换了好几个写法,比如basic_auth或者basic_authorize等等,都会报这个错

关注,我也出现类似错误。

没有加载 js 驱动

需要 登录 后方可回复, 如果你还没有账号请 注册新账号