Sha256: 6a4c66aaccce3c6f4a34578dd88eeb5c7a24f530e144300c3eb005c33c4c11f9

Contents?: true

Size: 1.82 KB

Versions: 2

Compression:

Stored size: 1.82 KB

Contents

#!/usr/bin/env ruby

module Safubot
  class KnownUser
	key :name, String # A unique identifier. Mainly for testing.

	validates_uniqueness_of :name, :allow_nil => true

	class << self
	  # Retrieves user by internal identifier.
	  def by_name(name)
		KnownUser.where(:name => name).first ||
		  KnownUser.create(:name => name)
	  end
	end
  end

  # Helpful methods for testing either via RSpec or IRB.
  module Test
    class << self
	  # Switches to the "safubot_testing" database and clears all data.
      def clean_environment
		MongoMapper.database = "safubot_testing"
        Request.destroy_all
		Query.destroy_all
        Response.destroy_all
		KnownUser.destroy_all
		Safubot::mode = :testing
        $bot = Safubot::Bot.new(:database => "safubot_testing")
      end

	  # Creates a Query-sourced testing Request.
	  # @param text The body of the Request.
	  def request(text)
		Query.create(:user => KnownUser.by_name('testing'), :text => text).make_request
	  end
    end
  end

  # Generic mediumless Request source.
  class Query
    include MongoMapper::Document
    safe

    key :text, String
    belongs_to :user, :polymorphic => true
    timestamps!

	one :request, :class_name => "Safubot::Request"

	# Find or create a Request sourced from this Query.
    def make_request
	  self.request || self.request = Request.create(:user => self.user, :text => self.text, :source => self)
    end

	def username
	  self.user.name
	end
  end

  class Bot
	# A generic "respond immediately" interface.
	# @param text The body of a Request to process.
	# @param user The user sending the request. Defaults to KnownUser.by_name('testing')
	def answer(text, user=nil)
	  user ||= KnownUser.by_name('testing')
	  query = Query.create(:user => user, :text => text)
	  req = query.make_request
	  process_request(req)
	  req.responses.first.text
	end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
safubot-0.0.9 lib/safubot/test_helper.rb
safubot-0.0.8 lib/safubot/test_helper.rb