夜鸣猪 发表于 2013-1-29 11:53:36

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)endGiven /^I have not uploaded the claim file to "(.*)"$/ do |url|   require 'fakeweb'FakeWeb.register_uri(:get, url, :status => ["404", "Not Found"])endGiven /^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/seleniumrequire 'app/models/monitoring/claim'require 'fakeweb'module Monitoringclass 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_webendend

selenium配置
#feature/support/selenium.rbWebrat.configure do |config|config.application_environment = :seleniumconfig.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 browserendclass ActiveSupport::TestCase   setup do |session|   session.host! "localhost:3001"   endendCucumber::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 supportrequire '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 = :railsconfig.open_error_files = true # Set to true if you want error pages to pop up in the browserend
页: [1]
查看完整版本: rails cucumber selenium 在ajax条件下的 mock测试 简例