路漫漫其修远兮,吾将上下而求索

发布新日志

  • Install ruby on Ubuntu

    2010-08-28 23:03:02

    Those days, i wanted to study ruby on linux os,  but when i tried to install ruby on ubuntu linux os, finded somethings were wrong in ruby-1.8.6, so i think you should download ruby-1.9.0.tar...from website.
    1. wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7.tar.gz  
    2. tar xjf ruby-1.8.7.tar.gz  
    3.   
    4. cd ruby-1.8.7  
    5. ./configure --prefix=/opt/ruby187  # prefix是安装目录  
    6. make        # 编译过程,比较长  
    7. sudo make install     # 比较快,大概就是复制文件到/opt/ruby187 
    8. 修改环境变量文件,将ruby的bin目录加入环境变量PATH中,我选择的/etc/profile文件,将以下两行加到文件最下面

      Shell代码
      1. # Ruby  
      2. PATH="$PATH:/opt/ruby187/bin"  

      用source命令刷新一下,再测试

      Shell代码
      1. source /etc/profile               # 使环境变量马上生效  
      2. ruby -v                                # ruby 1.8.7 ...... 
  • Question

    2010-08-26 09:29:09

    最近在使用watir写自动化测试用例,遇到了一些问题,目前还没有找到好的解决办法,现在记录下来,以备以后找到更好的解决办法
    1.想通过ruby代码来来删除已经安装的插件,这个目前没有解决办法。现在我是通过把安装插件的目录全部删除,gamexiu网站就不会识别出浏览gamexiu的这台电脑已经安装了插件,但是在进行后续操作的时候还是要手动的从控制面板里面去删除FileUtils.rm_rf "#{@temp_file}",但是使用windows自带的
    2.gamexiu网站使用php语言和ajax,javascript等,混合着yii框架。在对某任务页面进行操作的时候,遇到了iframe下包含小的html页面,虽然watir语言对iframe支持,但是在操作过程中总是access is denied,最终没有实现访问iframe里面html页面的办法.......
    3.使用autoit和watir对网站下载安装插件进行操作的过程中,总是遇到偶然现象,要么进程被死锁;要么autoit无法识别到要确认的按钮;要么在完成了安装后,没有执行后续的代码.......弄的我头大
    4.还是不太清楚应该怎样使用Test::Unint自带的方法记录下来error和failure信息,及他们的数量.......写出来的代码总是执行不下去



    要是访问我博客的好友们有什么更好的解决办法,告诉下我,谢谢。
    谢谢浏览我的空间
  • Why do I get an access denied error when trying to access a frame?

    2010-08-24 17:51:26

    http://wiki.openqa.org/display/WTR/Frames
  • how to exec exe file in ruby

    2010-08-10 09:22:49

    Yesterday, i registered a website "http://stackoverflow.com/", and submitted a question "http://stackoverflow.com/questions/3438304/how-to-exec-exe-file-and-quite-it-successfully-in-ruby"

    The question is
  • run exe file by using ruby

    2010-08-06 14:41:25

    It is very easy to do that, just one lin code

    exec("d:\\my_exe.exe")
  • how to delete not empty dir by using ruby

    2010-08-06 11:06:10

    I normally use FileUtils for that sort of thing, e.g.,

    require 'fileutils'
    FileUtils.rm_rf 'directory'
  • 使用watir 安装软件

    2010-08-04 10:51:19

    查看这个地址http://wiki.openqa.org/display/WTR/File+Downloads
  • Watir随笔(清除ie中cookies)

    2010-08-03 11:07:33

    Watir随笔(清除ie中cookies)

    require 'watir'
    require 'thread'
    require 'test/unit'
    require 'test/unit/ui/console/testrunner'
    require 'watir/testUnitAddons'
    require 'watir/cookiemanager'
    include Watir

    #clear the cookies
    print Watir::CookieManager::WatirHelper.getSpecialFolderLocation(Watir::CookieManager::WatirHelper::COOKIES)
    Watir::CookieManager::WatirHelper.deleteSpecialFolderContents(Watir::CookieManager::WatirHelper::COOKIES)

    #clear the cathes
    print Watir::CookieManager::WatirHelper.getSpecialFolderLocation(Watir::CookieManager::WatirHelper::INTERNET_CACHE)
    Watir::CookieManager::WatirHelper.deleteSpecialFolderContents(Watir::CookieManager::WatirHelper::INTERNET_CACHE)

  • end_form_tag

    2010-03-09 13:25:58

    先从简单开始,我想用Rails创建一个表单:
    (我用的Rails版本是2.0.2)

    <%=form_tag :action=> 'my_action' %>
    <%=end_form_tag %>

    然后在浏览器中会出现这样的错误:

    NameError in Chapter#myaction

    Showing chapter/myaction.html.erb where line #2 raised:

    undefined local variable or method `end_form_tag' for # <ActionView::Base:0x3662184>

    Extracted source (around line #2):

    1: <%=form_tag :action=>'myaction' %>
    2: <%=end_form_tag %>
    3:

    <%=end_form_tag %>
    这个应该使用</form>代替,因为end_form_tag 方法在rails 2.0版本后已经废弃了

  • rake db:migrate时报错

    2010-03-09 10:38:28

    如果使用最新的Rails 2.3与MySQL 5.1.3进行开发,很有可能你会遇到这个问题:
    在rake db:migrate时报错,提示

    Mysql::Error: query: not connected: CREATE TABLE `schema_migrations` (`version`
    varchar(255) NOT NULL) ENGINE=InnoDB

    检查日志,你会发现即使配置完全没有问题,运行 ruby script/dbconsole 也能够正常连接上,migrate依然会报错。那么到底是为什么呢?

    这是因为MySQL 5.1.3版本所带的libmysql.dll文件并不能很好的与Rails连接。所以你只需更换一个旧版本的libmysql.dll文件即可。

    http://instantrails.rubyforge.org/svn/t ... bmySQL.dll 处可以下载到旧版本的libmysql.dll文件,将其保存在ruby\bin\目录下即可。

    附:这个问题折腾了晓晓半个晚上啊……最终找到的解决方案原出处在此

  • ruby on rails数据库sqlite3

    2010-03-05 11:00:00

    rails默认使用的是sqlite3数据库,因此当你安装rails时候要把sqlite配置好了

    1.已经装好了ruby+rails

    2.去http://www.sqlite.org/sqlitedll-3_6_16.zip地址下载sqlitedll-3_6_16.zip ,解压

    3.将解压后的文件分别放入C:\ruby1.8\bin
    C:\WINDOWS\system
    C:\WINDOWS\system32

  • sqlitedll-3_6_16.zip – you can think of this one as actually being the SQLite database that you will install on your machine
  • 4.去http://www.sqlite.org/sqlite-3_6_16.zip地址下载sqlite-3_6_16.zip

  • sqlite-3_6_16.zip – this one is a command line utility that can be used to administer a SQLite database
  •     gem install sqlite3-ruby

  • 如何让Watir脚本在不同环境下运行 3

    2010-03-03 16:00:21

     

    (五)使用Watir::Waiter::wait_until进行等待操作

    使用过watir对网页进行测试的朋友,一定会遇到这样的问题。当使用sleep或者ie.wait的时候,由于网速太慢页面没有在制定的时间内页面没有下载完或者指定等待的时间太短,都会导致脚本不能找指定的html tag,系统会给出警告性语句,接下来的所有存在于这个单元测试的方法都会执行不了,rb会对剩下的所有方法给出同样的警告性错误,非常的让人头痛。

    (1)使用ie.wait进行等待操作。

    Ie.wait这个方法不好使用在于,它把确定网页是否加载完全交给了ie自己判断,所以有的时候ie会认为自己已经加载完整个网页,而这时ie其实是判断失误的。

    (2)使用sleep方法进行等待操作。

    Sleep  n ,n是时间数,就是说你想让你的网页进行等待操作都行,但是有的时候并不能够准确的评估出来网页加载所需要的准确时间,有的时候这个方法也是不那么非常好用的,并且如果你给的时间过长,会造成你的测试效率低。

    sleep 1 until ie.text.include? “new results are loaded”

    上面的例子使脚本一直处于等待状态,知道页面出现”new results are loaded” 才继续执行

    (3)使用wait_until方法进行等待操作。

    如果你的页面一直不出现“new results are loaded”怎么办?你要一直等待?还是关闭脚本重新来过?如果下次还是遇到相同问题怎么办??

    Watir中的Waiter类的“wait_until”方法 ,这个方法让watir一直等待,直到页面出现了所需要的内容,脚本就继续执行下面的步骤;如果在60秒内,页面没有出现所需要的内容,就给出警告性错误信息。

    wait_until {ie.text.include? “new results are loaded”}

    给朋友们一个简单的列子:

    require ‘watir’
    browser = Watir::Browser.start(’http://www.google.com’)
    # In this case all I care about is the text field existing, you could
    # check title, text, anything you’re expecting before continuing
    Watir::Waiter::wait_until { browser.text_field(:name, ‘q’).exists? }
    browser.text_field(:name, ‘q’).set(’ruby poignant’)

    如果想查看更详细的内容,请链接:

    http://wiki.openqa.org/display/WTR/How+to+wait+with+Watir

  • 如何让Watir脚本在不同环境下运行 2

    2010-03-03 15:59:34

     

    (四)使用watir对来对JavaScript. Pop Ups进行处理

    一直都是在半知半解的状态下使用autoit来对Javascript. pop ups进行处理,虽然可以处理成功,但是还是不太明确为什么要这样做才可以点击到“确定”按钮等。前阵子为了使脚本能够在不干扰本机用户的使用情况下正常运行,搜索资料查找到一个非常有用的方法。

    (我想如果你仔细读懂了这  个链接中所给出的内容,你处理弹出对话框的问题应该也没有太多的问题了。http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups

    该方法可以方便的让你的脚本正常运行,并且不影响本机用户的正常运行。并且这个方法不需要依靠autoit来运行脚本,仅仅使用win32ole方法来对弹出的对话框进行出来。

    步骤为:

    (1)              首先向库文件ie-class.rb添加如下代码,(库文件所在位置C:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.2\lib\watir\ie-class.rb)

    #/////////////////////////////////////////////////////////////////////////////
    #Name: clickprompt
    #Description: Waits for the popup to appear and then clicks the ok or cancel button
    #
    #Arguments: button: The button to be pressed – “OK” or “CANCEL”
    # txt: Text to be passed into the prompt dialog box
    # waitTime: the waiting time caluclated as waitingtime/0.2 currently set to 50 seconds
    #Returns: This returns the popup text if popup is found or ” if no popup is found
    #/////////////////////////////////////////////////////////////////////////////
    def clickprompt(but=”OK”,txt =”", waitTime = 10)
    tim = 0
    poptxt= ”
    while tim < waitTime
    sleep 0.2
    pophwnd = Win32API.new(”user32″, “GetWindow”, ‘Li’, ‘L’).Call(@ie.hwnd.to_i, 6)
    # the above returns any popup windows that are present for the specific window
    tim += 0.2
    tim += waitTime if pophwnd != 0
    end
    return ” if pophwnd == 0
    button = but.upcase
    outval = ‘ ‘ * 30
    Win32API.new(”user32″, “GetWindowText”, ‘Lpi’, ‘L’).Call(pophwnd,outval,30)
    popwndtitle = outval.rstrip.chomp(”00″) # window title stored here
    outval = nil
    #poptype = 0
    #alert and confirm have ie6 – Microsoft Internet Explorer
    #ie7 – Windows Internet Explorer
    #ie8 – Message from webpage
    if popwndtitle.include?(”Microsoft Internet Explorer”) ||
    popwndtitle.include?(”Windows Internet Explorer”) ||
    popwndtitle.include?(”Message from webpage”)
    #confirm and alerts have the above 3 window titles
    # poptype =1 means this is a javascript. alert tag
    #poptype = 1
    poptxt = handlepopup1(pophwnd,button)
    elsif popwndtitle.include?(”Explorer User Prompt”)
    #prompts have the above window title
    #poptype = 2
    poptxt = handlepopup2(pophwnd,button, txt)
    elsif popwndtitle.include?(”Connect to”)
    #authentication dialog
    #also make sure the username and password text fields are present – if present we got the auth dialog
    cntrlhwnd = 0
    cntrlhwnd = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 1002)
    #poptype = 3 if cntrlhwnd != 0 #verified the 2 textboxes are present to enter the values
    return ” if cntrlhwnd == 0
    poptxt = handlepopup3(pophwnd,button, prompt)
    end
    return poptxt
    end

    def handlepopup1(pophwnd, button)
    # handles the alerts and confirm dialogs
    #Yes there is a popupwindow… hence get the controlhandle for the text control – 65535
    cntrlhwnd = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 65535)
    #now get the text from the popup
    outval = ‘ ‘ * 900
    Win32API.new(”user32″, “GetWindowText”, ‘Lpi’, ‘L’).Call(cntrlhwnd,outval, 900)
    poptext = outval.rstrip.chomp(”00″)
    outval = nil

    #confirm ok-1 and cancel-2, alert ok-2
    cntrlhwndOK = 0
    cntrlhwndCANCEL = 0
    cntrlhwndOK = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 1)
    if cntrlhwndOK == 0 # only 1 button alert
    cntrlhwndOK = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 2)
    clickWin32Button(cntrlhwndOK) # done clicking javascript. ok button
    return poptext
    else # this is a confirm with 2 buttons
    cntrlhwndCANCEL = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 2)
    end
    button.include?(”OK”) ? clickWin32Button(cntrlhwndOK) : clickWin32Button(cntrlhwndCANCEL)
    #clickWin32Button(cntrlhwndCANCEL)
    return poptext
    end
    private :handlepopup1

    def handlepopup2(pophwnd, button, prompt)
    #handles prompt boxes which takes a value as input
    cntrlhwndOK = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 1)
    cntrlhwndCANCEL = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 2)

    # get handle to the text control from the prompt box
    cntrlpromptText = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 8132)
    #now get the text from the popup
    outval = ‘ ‘ * 200
    Win32API.new(”user32″, “GetWindowText”, ‘Lpi’, ‘L’).Call(cntrlpromptText,outval, 200)
    poptext = outval.rstrip.chomp(”00″)
    outval = nil

    cntrltextarea = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 8133)
    if prompt.size != 0
    sendmessage = Win32API.new(”user32″, “SendMessage”, ‘LLpp’, ‘L’)
    sendmessage.Call(cntrltextarea, 0×000C, ”, prompt) # calling sendmessage with WM_SETTEXT
    end
    button.include?(”OK”) ? clickWin32Button(cntrlhwndOK) : clickWin32Button(cntrlhwndCANCEL)
    return poptext
    end
    private :handlepopup2

    def handlepopup3(pophwnd, button, prompt)
    # handles the auth dialog box , 3 tries then the 401 page is shown
    cntrlhwnd = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 1002)
    cntrlusername = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(cntrlhwnd, 1003)
    cntrlpassword = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(cntrlhwnd, 1005)
    if prompt.size == 2
    sendmessage = Win32API.new(”user32″, “SendMessage”, ‘LLpp’, ‘L’)
    sendmessage.Call(cntrlusername, 0×000C, ”, prompt[0]) # calling sendmessage with WM_SETTEXT
    sendmessage.Call(cntrlpassword, 0×000C, ”, prompt[1]) # calling sendmessage with WM_SETTEXT
    end
    cntrlhwndOK = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 1)
    cntrlhwndCANCEL = Win32API.new(”user32″, “GetDlgItem”, ‘Li’, ‘L’).Call(pophwnd, 2)
    button.include?(”OK”) ? clickWin32Button(cntrlhwndOK) : clickWin32Button(cntrlhwndCANCEL)

    end
    private :handlepopup3

    def clickWin32Button(cntrlhwnd)
    Win32API.new(”user32″, “SendMessage”,’LLLL’,'L’).Call(cntrlhwnd, 0×0006, 1,0)
    Win32API.new(”user32″, “SendMessage”,’LLLL’,'L’).Call(cntrlhwnd, 0×00F5, 0,0)
    end
    private :clickWin32Button
    (2)对于系统语言的不同,浏览器弹出来的对话框及对话框中的一些按钮也是不尽相同的,所以可能需要像你修改下刚刚所添加进来的clickprompt方法。

    比如在中文vista操作系统下的ie7浏览器,弹出来的对话框的title值为中文,所以需要修改下 clickprompt方法下的if语句

    if popwndtitle.include?(”Microsoft Internet Explorer”) ||
    popwndtitle.include?(”Windows Internet Explorer”) ||
    popwndtitle.include?(”Message from webpage”) ||popupwndtitle.include?(”来自网页的消息”)

  • 如何让Watir脚本在不同环境下运行 1

    2010-03-03 15:58:48

     

    Watir自动化测试

    最近一直在忙着修改我的watir自动化脚本,为了让脚本可以在不同的浏览器上及不同的操作系统上都能够正常的运行,真是费尽脑汁去查找相关的资料。嘿嘿,在经理的帮助下,我的脚本终于可以在不同的系统不同的浏览器上运行了。

    (一)watir对中文网页的支持

    Watir现在的版本已经升级到1.6.5,但是这个版本对中文网页的支持却不如1.6.2,所以当测试中文网页的时候,你需要修改下类库中的win32ole.rb文件,具体路径为:ruby\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir,将win32ole.rb文件中的WIN32OLE.codepage = WIN32OLE::CP_UTF8更改为:WIN32OLE.codepage =  WIN32OLE::CP_ACP。

    codepage值有下面这些,不行的话可以逐个修改下

    WIN32OLE::CP_ACP

    WIN32OLE::CP_OEMCP

    WIN32OLE::CP_MACCP

    WIN32OLE::CP_THREAD_ACP

    WIN32OLE::CP_SYMBOL

    WIN32OLE::CP_UTF7

    WIN32OLE::CP_UTF8

    (二)相对工作路径

    使用excel文件对watir自动化脚本进行数据驱动。为了方便脚本的管理,在读取excel文件的时候,应该需要使用相对路径。

    获得当前执行文件的文件名:_FILE_

    获得当前文件的目录:File.dirname(_FILE_)

    获得当前执行文件的目录完整路径:

    Require ‘pathname’

    Pathname.new(File.dirname(_FILE_)).realpath

    获得当前执行文件的完整路径:

    Require ‘pathname’

    Pathname.new(_FILE_).realpath

    File.basename(filename[, suffix]):

    返回filename中的最后一条斜线后面的部分。若给出了参数suffix且它和filename的尾部一致时,该方法会将其删除并返回结果。

    File.basename(filename[, suffix]):

    返回filename中的最后一条斜线后面的部分。若给出了参数suffix且它和filename的尾部一致时,该方法会将其删除并返回结果。

    File.dirname(filename) :

    以字符串的形式返回filename中最后一条斜线之前的部分。若文件名中不含斜线,则返回”.”(当前目录)。

    File.expand_path(path[, default_dir]):

    path展开为绝对路径后返回该路径字符串。若path是相对路径则以default_dir为基准进行扩展。若没有default_dir或其值为nil时将使用当前目录。

    因此当需要获得excel文件要:

    File.dirname(File.expand_path(”_FILE_”))+”/****.xls

    但是如果你所需要的excel文件在根目录下就可以这样写:

    File.dirname(File.expand_path(”_FILE_”))+”*****.xls

    (三)获取操作系统的语言

    有的时候自动化测试需要根据操作系统语言,来决定脚本应该怎样运行。比如对于中文系统的浏览器,popoup box给出的button会是中文的“确定“,但是在英文系统下的浏览器,popoup box给出的button会是中文的“ok“或者”cancel”.

    globalAlloc= Win32API.new(’kernel32′, ‘GetSystemDefaultUILanguage’,”, ‘I’)

    puts globalAlloc.Call()

  • ruby on rails 安装

    2010-03-03 15:57:03

    Ruby on Rails安装指南(Ruby 1.8.6+Rails 2.0.2)
    2009-09-23 11:04

    http://developer.51cto.com 2009-08-27 10:21 佚名 网络转载 我要评论(0)

    Ruby on Rails安装,有人说难,但其实也很方便。要基于ruby开发应用程序,我们必须安装ruby、gem、rails、mongrel。

    Ruby on Rails安装步骤解析

    第一,到官方网站上下载最新的Ruby One-Click Installer版本(已经自带了RubyGems,一个Ruby标准的包管理器),下载地址为:http://rubyforge.org/frs/download.php/29263/ruby186-26.exe,下载后的文件名为:ruby186-26.exe。

    第二,安装ruby,双击后下一步下一步。。。,完成安装工作,默认将安装在c:/ruby目录。

    重新打开命令行,打入ruby -v可以查询ruby的版本。

    第三,下载rails,本文下载的是rails2.0.2版本(下载后的文件名是:rails-2.0.2.zip),下载地址为:http://rubyforge.org/frs/download.php/29361/rails-2.0.2.zip

    第四,安装rails,建议不要使用网上所说的在命令行模式下打入gem install rails --include-dependencies,因为这种安装方式需要连接到网络,并且安装是经常失败的。而是下载一个stand-alone packages版本,然后在本地安装。将文件rails-2.0.2.zip copy到ruby的安装目录,并将rails-2.0.2.zip改名为rails.zip。不然,安装的时候还是到网上去找。

    在命令行下打入:gem install rails,几秒钟即完成了安装工作。注意:压缩文件不需要解压缩,当然,也可以解压缩,进入各个插件目录一个一个安装也不成问题。

    安装rails同时将依次安装:

    1,activesupport

    2,activerecord

    3,actionpack

    4,actionmailer

    5,actionwebservice

    6,rails

    这几个gem文件其实都可以在rails.zip这个压缩包当中的vendor/rails找到

    安装完后可以在命令行下打入:rails -v可以查看rails的版本。

    第五,下载Mongrel,当前最新版本为:1.1.4,下载地址为:http://rubyforge.org/frs/download.php/33195/mongrel-1.1.4-x86-mswin32-60.gem

    安装mogrel还需要额外地下载gem plugin、daemons、fastthread、cgi_multipart_eof_fix,下载地址为

    gen_plugin:http://rubyforge.org/frs/download.php/27044/gem_plugin-0.2.3.gem

    daemons:http://rubyforge.org/frs/download.php/34222/daemons-1.0.10.gem

    fastthread:http://rubyforge.org/frs/download.php/29508/fastthread-1.0.1-i386-mswin32.gem

    cgi_multipart_eof_fix:http://rubyforge.org/frs/download.php/27040/cgi_multipart_eof_fix-2.5.0.gem

    第六,安装mongrel。

    gem install gem_plugin-0.2.3.gem

    gem install daemons-1.0.10.gem

    gem install fastthread-1.0.1-i386-mswin32.gem

    gem install cgi_multipart_eof_fix-2.5.0.gem

    gem install mongrel-1.1.4-x86-mswin32-60.gem

    第七,创建测试的rails应用程序。

    进入想创建工程的目录,假如工程名为hello,在命令行下打下:rails hello

    此时,系统将自动创建ruby on rails的应用程序,自动初始化目录结构及一些基本性的东东。

    第八,启动rails

    进入hello目录,在命令行下打入:mongrel_rails start -d启动mongrel服务器。

    默认的的服务器将占用3000端口,最后,打开IE,测试一下是否能显示ruby on rails的主界面。

    到此,ruby on rails安装成功。

    当然,你也可以下载一些集成开发环境,那有很多工作都可以省略掉。但如果是使用最普通的命令行模式,或许,你能体验更多,虽然中间流了不少汗水,谋杀多少脑细胞,但是,乐在其中!哈哈

    最后讲一句:如果直接安装InstantRails,下载地址为:http://rubyforge.org/frs/download.php/29867/InstantRails-2.0-win.zip。那什么事情也不用干了,因为包括ruby、rails、Mongrel 、apache都全部已经打包在一起了。不过,要了解整个安装过程,建议还是一个一个安装。建议初学者刚开始还是多做几次比较好!

  • ruby连接mysql的方法

    2010-01-21 17:16:10


    今天尝试用ruby连接mysql的方法,很简单,记下来

    1. 首先安装ruby1.8.6

    2. 然后下载mysql-2.8.1-x86-mswin32.gem

    下载地址http://rubyforge.org/projects/mysql-win  

    3. 然后到系统命令行中输入:gem install D:\mysql-2.8.1-x86-mswin32.gem (注意:文中所有路径可以任意指定,但是确保路径下的文件确实存在)

    4. 然后把比如E:\ruby\lib\ruby\gems\1.8\gems\mysql-2.8.1-x86-mingw32\lib\1.8

    下的mysql.so(或者mysql_api.so)放到比如E:\ruby\lib\ruby\site_ruby\1.8\i386-msvcrt

    再把Mysql安装目录下的bin目录下的libmysql.dll拷到比如E:\ruby\bin

     

    测试代码:

    require "mysql"

    dbc=Mysql.real_connect('数据库IP','root','******','数据库名称')

    res=dbc.query('select id from test')

    while row=res.fetch_row do

    puts "#{row[0]}" 

    end 

  • RUBY获取当前的执行文件的路径和目录

    2009-12-16 13:41:40

     

    获得当前执行文件的文件名:

    __FILE__

    获得当前文件的目录

    File.dirname(__FILE__)

    获得当前执行文件的完整路径

    require ‘pathname’
    Pathname.new(__FILE__).realpath

    获得当前执行文件的目录完整路径

    require ‘pathname’
    Pathname.new(File.dirname(__FILE__)).realpath

    如果使用$0: $0是整个ruby执行文件最顶层文件的路径。因此使用if __FILE__==$0可以判断当前ruby文件是被引用还是被执行。

    File.basename(filename[, suffix]):返回filename中的最后一条斜线后面的部分。若给出了参数suffix且它和filename的尾部一致时,该方法会将其删除并返回结果。
    File.dirname(filename) :以字符串的形式返回filename中最后一条斜线之前的部分。若文件名中不含斜线,则返回"."(当前目录)。
    File.expand_path(path[, default_dir]) path展开为绝对路径后返回该路径字符串。若path是相对路径则以default_dir为基准进行扩展。若没有default_dir或其值为nil时将使用当前目录。开头的~会被扩展为主目录(使用环境变量HOME),而~USER会被扩展为相应用户的主目录。

    问题:

          脚本放在根目录下可以通过File.dirname(File.expand_path("_FILE_"))+"emailNikName.xls"这个方法来获取脚本;但是如果根目录下的某个文件夹下,就一定要在_"emailNikName.xls"前加上“/”,即_"/emailNikName.xls"。

         没有查到好办法,只有通过判断当前目录是否为根目录来决定如何运行脚本,期待更好的办法。如果有那些朋友有,可以留言给我...

     

  • ruby读取目录和文件的file/directories类

    2009-12-16 11:42:13

    Directories in Ruby:

    All files are contained within various directories, and Ruby has no problem handling these too. Whereas the File class handles files, directories are handled with the Dir class.

    所有的文件都是包含在各种不同的目录中,RUBY能够很好的处理它。File类处理文件,Dir类处理目录

    Navigating Through Directories:

    To change directory within a Ruby program, use Dir.chdir as follows. This example changes the current directory to /usr/bin.

    使用Dir.chdir来改变当前目录

    Dir.chdir("/usr/bin")
    

    You can find out what the current directory is with Dir.pwd:

    使用Dir.pwd来查看当前目录

    puts Dir.pwd # This will return something like /usr/bin
    

    You can get a list of the files and directories within a specific directory using Dir.entries:

    使用Dir.entries来查看一个特定目录下的所有文件

    puts Dir.entries("/usr/bin").join(' ')
    

    Dir.entries returns an array with all the entries within the specified directory. Dir.foreach provides the same feature:

    Dir.entries 将以数组的形式放回特定目录下的所有文件,Dir.foreach也可以这样做

    Dir.foreach("/usr/bin") do |entry|
       puts entry
    end
    

    An even more concise way of getting directory listings is by using Dir's class array method:

     

    Dir["/usr/bin/*"]
    

    Creating a Directory:

    The Dir.mkdir can be used to create directories:

    Dir.mkdir("mynewdir")
    

    You can also set permissions on a new directory (not one that already exists) with mkdir:

    NOTE: The mask 755 sets permissions owner, group, world [anyone] to rwxr-xr-x where r = read, w = write, and x = execute.

    Dir.mkdir( "mynewdir", 755 )
    

    Deleting a Directory:

    The Dir.delete can be used to delete a directory. The Dir.unlink and Dir.rmdir perform. exactly the same function and are provided for convenience.

    Dir.delete("testdir")
    

    Creating Files & Temporary Directories:

    Temporary files are those that might be created briefly during a program's execution but aren't a permanent store of information.

    Dir.tmpdir provides the path to the temporary directory on the current system, although the method is not available by default. To make Dir.tmpdir available it's necessary to use require 'tmpdir'.

    You can use Dir.tmpdir with File.join to create a platform-independent temporary file:

    require 'tmpdir'
       tempfilename = File.join(Dir.tmpdir, "tingtong")
       tempfile = File.new(tempfilename, "w")
       tempfile.puts "This is a temporary file"
       tempfile.close
       File.delete(tempfilename)
    

    This code creates a temporary file, writes data to it, and deletes it. Ruby's standard library also includes a library called Tempfile that can create temporary files for you:

    require 'tempfile'
       f = Tempfile.new('tingtong')
       f.puts "Hello"
       puts f.path
       f.close
    

     

    The puts Statement:

    In previous chapters, you assigned values to variables and then printed the output using puts statement.

    The puts statement instructs the program to display the value stored in the variable. This will add a new line at the end of each line it writes.

    Example:

    #!/usr/bin/ruby
    
    val1 = "This is variable one"
    val2 = "This is variable two"
    puts val1
    puts val2
    

    This will produce following result:

    This is variable one
    This is variable two
    

    The gets Statement:

    The gets statement can be used to take any input from the user from standard screen called STDIN.

    Example:

    The following code shows you how to use the gets statement. This code will prompt the user to enter a value, which will be stored in a variable val and finally will be printed on STDOUT.

    #!/usr/bin/ruby
    
    puts "Enter a value :"
    val = gets
    puts val
    

    This will produce following result:

    Enter a value :
    This is entered value
    This is entered value
    

    The putc Statement:

    Unlike the puts statement, which outputs the entire string onto the screen, the putc statement can be used to output one character at a time.

    Example:

    The output of the following code is just the character H:

    #!/usr/bin/ruby
    
    str="Hello Ruby!"
    putc str
    

    This will produce following result:

    H
    

    The print Statement:

    The print statement is similar to the puts statement. The only difference is that the puts statement goes to the next line after printing the contents, whereas with the print statement the cursor is positioned on the same line.

    Example:

    #!/usr/bin/ruby
    
    print "Hello World"
    print "Good Morning"
    

    This will produce following result:

    Hello WorldGood Morning
    

    Opening and Closing Files:

    Until now, you have been reading and writing to the standard input and output. Now we will see how to play with actual data files.

    The File.new Method:

    You can create a File object using File.new method for reading, writing, or both, according to the mode string. Finally you can use File.close method to close that file.

    Syntax:

    aFile = File.new("filename", "mode")
       # ... process the file
    aFile.close
    

    The File.open Method:

    You can use File.open method to create a new file object and assign that file object to a file. However, there is one difference in between File.open and File.new methods. The difference is that the File.open method can be associated with a block, whereas you cannot do the same using the File.new method.

    File.open("filename", "mode") do |aFile|
       # ... process the file
    end
    

    Here is a list of The Different Modes of Opening a File:

    Modes Description
    r Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
    r+ Read-write mode. The file pointer will be at the beginning of the file.
    w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
    w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
    a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
    a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

    Reading and Writing Files:

    The same methods that we've been using for 'simple' I/O are available for all file objects. So, gets reads a line from standard input, and aFile.gets reads a line from the file object aFile.

    However, I/O objects provides additional set of access methods to make our lives easier.

    The sysread Method:

    You can use the method sysread to read the contents of a file. You can open the file in any of the modes when using the method sysread. For example :

    #!/usr/bin/ruby
    
    aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")
    if aFile
       content = aFile.sysread(20)
       puts content
    else
       puts "Unable to open file!"
    end
    

    This statement will output the first 20 characters of the file. The file pointer will now be placed at the 21st character in the file.

    The syswrite Method:

    You can use the method syswrite to write the contents into a file. You need to open the file in write mode when using the method syswrite. For example :

    #!/usr/bin/ruby
    
    aFile = File.new("/var/www/tutorialspoint/ruby/test", "r+")
    if aFile
       aFile.syswrite("ABCDEF")
    else
       puts "Unable to open file!"
    end
    

    This statement will write "ABCDEF" into the file.

    The each_byte Method:

    This method belongs to the class File. The method each_byte is always associated with a block. Consider the following code sample: :

    #!/usr/bin/ruby
    
    aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")
    if aFile
       aFile.syswrite("ABCDEF")
       aFile.each_byte {|ch| putc ch; putc ?. }
    else
       puts "Unable to open file!"
    end
    

    Characters are passed one by one to the variable ch and then displayed on the screen as follows:

    T.h.i.s. .i.s. .l.i.n.e. .o.n.e.
    .T.h.i.s. .i.s. .l.i.n.e. .t.w.o.
    .T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e.
    .A.n.d. .s.o. .o.n.......
    

    The IO.readlines Method:

    The class File is a subclass of the class IO. The class IO also has some methods which can be used to manipulate files.

    One of the IO class methods is IO.readlines. This method returns the contents of the file line by line. The following code displays the use of the method IO.readlines:

    #!/usr/bin/ruby
    
    arr = IO.readlines("/var/www/tutorialspoint/ruby/test")
    puts arr[0]
    puts arr[1]
    

    In this code, the variable arr is an array. Each line of the file test will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file.

    The IO.foreach Method:

    This method also returns output line by line. The difference between the method foreach and the method readlines is that the method foreach is associated with a block. However, unlike the method readlines, the method foreach does not return an array. For example:

    #!/usr/bin/ruby
    
    IO.foreach("test"){|block| puts block}
    

    This code will pass the contents of the file test line by line to the variable block, and then the output will be displayed on the screen.

    Renaming and Deleting Files:

    You can rename and delete files programmatically with Ruby with the rename and delete methods.

    Following is the example to rename an existing file test1.txt:

    #!/usr/bin/ruby
    
    # Rename a file from test1.txt to test2.txt
    File.rename( "test1.txt", "test2.txt" )
    
    

    Following is the example to delete an existing file test2.txt:

    #!/usr/bin/ruby
    
    # Delete file test2.txt
    File.delete("text2.txt")
    
    

    File Modes and Ownership:

    Use the chmod method with a mask to change the mode or permissions/access list of a file:

    Following is the example to change mode of an existing file test.txt to a mask value:

    #!/usr/bin/ruby
    
    file = File.new( "test.txt", "w" )
    file.chmod( 0755 )
    
    

    Following is the table which can help you to choose different mask for chmod method:

    Mask Description
    0700 rwx mask for owner
    0400 r for owner
    0200 w for owner
    0100 x for owner
    0070 rwx mask for group
    0040 r for group
    0020 w for group
    0010 x for group
    0007 rwx mask for other
    0004 r for other
    0002 w for other
    0001 x for other
    4000 Set user ID on execution
    2000 Set group ID on execution
    1000 Save swapped text, even after use

    File Inquiries:

    The following command tests whether a file exists before opening it:

    #!/usr/bin/ruby
    
    File.open("file.rb") if File::exists?( "file.rb" )
    
    

    The following command inquire whether the file is really a file:

    #!/usr/bin/ruby
    
    # This returns either true or false
    File.file?( "text.txt" ) 
    
    

    The following command finds out if it given file name is a directory:

    #!/usr/bin/ruby
    
    # a directory
    File::directory?( "/usr/local/bin" ) # => true
    
    # a file
    File::directory?( "file.rb" ) # => false
    

    The following command finds whether the file is readable, writable or executable:

    #!/usr/bin/ruby
    
    File.readable?( "test.txt" )   # => true
    File.writable?( "test.txt" )   # => true
    File.executable?( "test.txt" ) # => false
    

    The following command finds whether the file has zero size or not:

    #!/usr/bin/ruby
    
    File.zero?( "test.txt" )      # => true
    

    The following command returns size of the file :

    #!/usr/bin/ruby
    
    File.size?( "text.txt" )     # => 1002
    

    The following command can be used to find out a type of file :

    #!/usr/bin/ruby
    
    File::ftype( "test.txt" )     # => file
    

    The ftype method identifies the type of the file by returning one of the following: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.

    The following command can be used to find when a file was created, modified, or last accessed :

    #!/usr/bin/ruby
    
    File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008
    File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008
    File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008
  • watir的测试用例

    2009-12-14 14:33:42

    I think this  http://www.ibm.com/developerworks/cn/opensource/os-cn-watir/index.html is very useful link.

    运用 Ruby 单元测试框架来管理和调用测试用例

    Ruby 提供了完善的单元测试框架。在 Watir 程序开发中,测试人员可以通过继承该框架,很方便地编写自动测试用例以及测试用例集 (Test Suites) 。以下是一些在 Watir 程序开发过程中常用到的类和模块

    • Test::Unit::Assertions,该模块提供了多种断言 (Assert) 方法,可用于测试结果的验证,如操作对象的状态的判定(如页面某对象是否存在,是否可用),或者消息显示是否与期望值匹配等
      • assert($ie.area(:alt, 'Table Buttons').exists?)
      • assert($ie.radio(:name, "box1").enabled?)
      • assert_match(test.html/, browser.link(:class_name, 'test').href)
      • assert_equal( ie.text_field(:id, "text2"), "Hello World" )
    • Test::Unit::TestCase 定义了测试用例类,它包括两个非常有用的公共方法:setup(), teardown(),它们分别会在每个测试用例启动前和运行后被调用。所以 Setup() 通常用于准备测试环境和测试数据,如打开 IE 窗口,登录应用,打开数据文件之类操作;而 teardown() 则用于释放资源和还原测试环境,如关闭 IE 窗口,退出应用等。除此之外,用户可自定义其他测试用例方法,只要方法名遵守一定的命名规则,即以“ test_ ”为前缀,在程序运行时测试用例就会按照方法名的字母排列顺序被自动调用。比如在下面的样例代码中,方法被调用的顺序为:

      图 12. 方法被调用的顺序
      方法被调用的顺序



      清单 2. 测试用例调用
         require  'Watir'                                       # 引入 Watir 库
      require 'test/unit'                               # 引入 Test::Unit 库
      class TC_MyTest1 < Test::Unit::TestCase         # 继承类 Test::Unit::TestCase 
      include Watir::Exception 
      include Watir::ScreenCapture 
       def setup 
            getEnvInfor ( ‘ Env1 ’ )                      # 获取环境信息
            if ! defined? $logger                     # 初始化日志
            		 $logger = LoggerFactory.start_xml_logger(FILE_PREFIX)
            		 end
      			if !defined? $screen                      # 初始化截屏对象
            		 $screen = Watir::ScreenCapture.new
            		 end
      				if !defined? $browser                 # 初始化 IE 浏览器
         $browser = Watir::IE.attach(:url, "https://localhost:9043/ibm/console")
            		 end
            		 login($USERNAME, $PASSW0RD)                    # 登录应用
       end 
      
       def teardown 
          logout()                                      # 退出应用
          $browser.close if defined? $browser             # 关闭 IE 浏览器
       end
       def test_testcase1           # 测试用例 1 
       $logger.log( “ Test Case 1 ” ) 
       $browser.button(:type, ‘ submit ’ ).click 
            ... 
       end
       def test_testcase2    # 测试用例 2 
       $logger.log( “ Test Case 2 ” ) 
       $browser.inputfield(:id, ‘ j_username ’ ).click 
       ... 
       end 
      
       end

    • Test::Unit::TestSuite 为测试用例集,用户可以将逻辑相近的测试用例添加到某测试用例集中,当运行该集合时,其中的每个测试用例会被按序调用。
      require 'test/unit/testsuite' 
       require  'TC_MyTest1' 
       require  'TC_MyTest2'
       class TS_MyTests
        def  self.suite 
          suite = Test::Unit::TestSuite.new               # 创建一个测试用例集实例
          suite << TC_MyTest1.suite                         # 将 TC_MyTest1 加入测试用例集
          suite << TC_MyTest2.suite                         # 将 TC_MyTest2 加入测试用例集
          ...
          return  suite
         end
        end 
      	 Test::Unit::UI::Console::TestRunner.run(TS_MyTests) # 运行测试用例集

      • Test::Unit::UI::Console::TestRunner 用于运行测试用例或测试用例集,
      • Test::Unit::TestResult 用于结果报告,所提供的接口可用于统计测试用例中运行成功 , 失败 , 出错的个数。在 Eclipse 输出窗口的 Test::Unit 栏,我们可以看到测试用例的运行结果。

  • autoit

    2009-12-14 13:47:53

    学习auotit所用的知识,慢慢补充ing

    1.使用spy++来查找popup对话框的类,类是一定不会改变的,因此a=autoit.WinWait("[Class:#32770]","",1)可以这样写。使用("[Class:#32770]"来代替title

  • 371/212>

    我的栏目

    数据统计

    • 访问量: 40166
    • 日志数: 76
    • 图片数: 2
    • 建立时间: 2007-11-02
    • 更新时间: 2011-08-13

    RSS订阅

    Open Toolbar