我们在这里做了一个简单的代码示例,是关于Ruby DSL测试的一个小的实验。希望通过对这段代码的解读,大家可以进一步了解Ruby语言的含义。#t#
做了一个小小的demo。如果成型的话,测试人员就可以这样写TC了。
这是一段检查百度搜索,然后验证的小demo。(实际测试当然不会这样子了)
host "www.baidu.com"
port 80
page "s"
field "wd","足球"
field "sourceid","Mozilla-search"
get
check_content "足球"
check_content "体育"
把以上内容存到文件里,系统就可以自动运行了。
登陆baidu,查询“足球”,然后检查里面是否有“体育”。
Ruby DSL测试定义代码如下
- # To change this template,
choose Tools | Templates- # and open the template in the editor.
- require 'open-uri'
- class MyDSL
- def self.dsl_accessor(*symbols)
- symbols.each { |sym|
- class_eval %{
- def #{sym}(*val)
- if val.empty?
- @#{sym}
- else
- @#{sym} = val.size == 1 ? val[0] : val
- end
- end
- }
- }
- end
- def method_missing(sym, *args)
- self.class.dsl_accessor sym
- puts "method missing #{sym}, #{args}"
- send(sym, *args)
- end
- attr_accessor :query
- dsl_accessor :test
- def self.load(filename)
- dsl = new
- dsl.instance_eval(File.read
(filename), filename)- puts File.read(filename)
- dsl
- end
- def self.loads(filename)
- dsl = new
- dsl.instance_eval(filename)
- dsl
- end
- def field(field_string,value)
- puts "#{field_string}=#{value}"
- if ! @query
- @query="#{field_string}=#{value}"
- else
- @query="#{@query}&#{field_string
}=#{value}"- end
- puts @query
- end
- def get
- puts 'get'
- @request="http://#{@host}:#
{@port}/#{@page}?#{@query}"- puts @request
- @result=open(@request)
- end
- def check_content(s)
- tmp=@result.read.scan(s).uniq
- if tmp.length!=0
- puts "found"
- puts tmp
- else
- puts "not found"
- end
- end
- def post
- puts 'post'
- end
- end#class MyDSL
- dsl=MyDSL.loads('
- host "www.baidu.com"
- port 80
- page "s"
- field "wd","xxxxxxx"
- field "sourceid","Mozilla-search"
- field "yy",0.222
- parameter 0.55,2.1,[2,3,4],
{:a=>7,:b=>8,:c=>9}- get
- check_content "xxx"
- check_content "ffffffffffffff"
- ')
- p dsl
- p dsl.instance_variables
以上这段代码示例就是Ruby DSL测试的相关方法介绍。