Capybara 主要是用来测试 rails 和 Rack 应用的。
Capybara helps you test Rails and Rack applications by simulating how a real user would interact with your app. It is agnostic about the driver running your tests and comes with Rack::Test and Selenium support built in. WebKit is supported through an external gem.
我们主要用 Capybara 和 Webdriver 结合起来进行网页自动化测试。那 Capybara 和 Selenium WebDriver 的区别是什么呢?盗用 watirmelon 的理念 :
比如 Selenium WebDriver ,使用的是最原始的 api 来操作元素。使用 Selenium WebDriver 写网页自动化,就感觉是手撕,生吃牛肉一样。
比如 watir-webdriver,watir-webdriver 封装了 Selenium WebDriver 的 api,使得 api 使用起来更加方便。 使用 watir-webdriver 写网页自动化,就不在是生吃牛肉了,可能在吃半成熟的牛肉粒了。
比如 Capybara DSL, 这种描述性语言让你感觉自己是在和人打交道,而不是和编程语言。 使用 DSL 写网页自动化,就感觉你已经看不见任何牛肉相关的原料了,你可能在吃一根香肠。
感觉很形象,虽然我觉得第一层和第二层,真心没啥差别,作为一个优雅的测试工程师,还是坐在麦当劳吃最近最火的不素之霸比较高档。
从这个牛肉图,可以看出 Capybara 所在的地方,也可以看出他背后其实也是是驱动 WebDriver 的,再抄一张图:
当然,appium 出来之后,这个背后的驱动就需要多一种。 作为遵循 WebDriver protocol 的 appium,其实和 WebDriver 没有太大的差别。appium_capybara 就应运而生。
appium_capybara 事实上是作为 Capybara 下的一个驱动的存在。所以最为关键的地方就是在 Capybara 的世界里注册一个新的 driver。
require 'appium_capybara'
desired_caps_ios = {
platform: "Mac",
deviceName: "iPhone Simulator",
platformName: "iOS",
platformVersion: "7.1",
app: "full/path/to/app.zip"
}
url = "http://localhost:4723/wd/hub" # or a sauce labs url
Capybara.register_driver(:appium) do |app|
appium_lib_options = {
server_url: url
}
all_options = {
appium_lib: appium_lib_options,
caps: desired_caps_ios
}
Appium::Capybara::Driver.new app, all_options
end
Capybara.default_driver = :appium
Appium::Capybara::Driver
继承于 Capybara::Selenium::Driver, 初始化的时候需要传入app
和 一个 hash
。这个 hash
包含 caps
和 appium_lib
,在初始化 browser 的时候,使用这个 hash
创建 Appium driver。
# override
#
# Creates and starts a new appium driver.
# To access the browser without creating one use @browser
def browser
unless @browser
@appium_driver = Appium::Driver.new @options
# browser is the standard selenium driver without any appium methods
@browser = @appium_driver.start_driver
end
@browser
end
# default to {} to prevent nil.fetch and other nil errors
@caps = opts[:caps] || {}
appium_lib_opts = opts[:appium_lib] || {}
当然这个 hash 也可以以文本形式存在,比如放在 appium.txt 中,
[caps]
platformName = "ios"
deviceName ="iPhone Simulator"
app = "./UICatalog.app.zip"
platformVersion = "8.1"
[appium_lib]
sauce_username = ""
sauce_access_key = ""
然后使用 Appium.load_appium_txt 导入。
说那么多,其实都是废话,我们来看看怎么使用 appium_capybara。 官方的用例是使用 rspec
。RSpec 在淘宝测试里有个系列,大家可以移步看下。 http://www.taobaotest.com/blogs/qa?bid=11663。目前 appium_capybara 官方的目录结构如下:
➜ example git:(master) ✗ tree
.
├── Gemfile
├── Gemfile.lock
├── UICatalog.app.zip
├── appium.txt
├── readme.md
└── spec
├── capybara_init.rb
├── home_page.rb
├── ios_example_spec.rb
└── spec_helper.rb
1 directory, 9 files
官方代码,亲测通过,ruby 版本 2.1.4