`

rails cucumber selenium 在ajax条件下的 mock测试 简例

阅读更多
代码的功能是依赖外部其它网络的,所以,测试需要模拟外部的条件

如果只是cucumber测试可以直接在definitions里写mock
Given /^I have uploaded the claim file to "(.*)"$/ do |url| 
  require 'fakeweb'
  FakeWeb.register_uri(:get, url, :body => @current_user.id.to_s)
end

Given /^I have not uploaded the claim file to "(.*)"$/ do |url| 
  require 'fakeweb'
  FakeWeb.register_uri(:get, url, :status => ["404", "Not Found"])
end

Given /^I have uploaded an invalid claim file to "(.*)"$/ do |url|
  require 'fakeweb'
  FakeWeb.register_uri(:get, url, :body => "abc123def456")
end


以上,表示我们准备了外部的url并且保证外部url可以返回的结果。

然而,我们的页面有ajax调用
所以要用selenium配置见底
而用selenium就会有异步调用的问题,上面的写法就不能找到,而会访问真正的url不是模拟的。

那么,可以如下解决:
#test/mocks/selenium
require 'app/models/monitoring/claim'
require 'fakeweb'
module Monitoring
  class Claim
    
    def can_verify_ownership_with_fake_web
      if index.url == 'http://notmatch.com'
        FakeWeb.register_uri(:get, index.url + "/yottaa.html", :body => "no such code")
      elsif index.url == 'http://nofilefound.com'
        FakeWeb.register_uri(:get, index.url + "/yottaa.html", :status => ["404", "Not Found"])
      else
        FakeWeb.register_uri(:get, index.url + "/yottaa.html", :body => user.id.to_s)
      end
      can_verify_ownership_without_fake_web
    end
    
    alias_method_chain :can_verify_ownership, :fake_web
  end
end


selenium配置
#feature/support/selenium.rb
Webrat.configure do |config|
  config.application_environment = :selenium
  config.selenium_browser_startup_timeout = 180 
  config.mode = :selenium 
  config.open_error_files = true # Set to true if you want error pages to pop up in the browser
end

class ActiveSupport::TestCase 
  setup do |session| 
    session.host! "localhost:3001" 
  end
end

Cucumber::Rails::World.use_transactional_fixtures = true


还有环境配置
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')

require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/rspec'
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'

require 'webrat'
require 'webrat/core/matchers'

require 'email_spec/cucumber'
require 'spec/stubs/cucumber'

Webrat.configure do |config|
  config.mode = :rails
  config.open_error_files = true # Set to true if you want error pages to pop up in the browser
end

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics