Class: Screenplay::ApiActor

Inherits:
Actor
  • Object
show all
Defined in:
lib/screenplay/actors/api.rb

Instance Attribute Summary collapse

Attributes inherited from Actor

#name

Instance Method Summary collapse

Methods inherited from Actor

descendants, #initialize

Constructor Details

This class inherits a constructor from Screenplay::Actor

Instance Attribute Details

#cookiesObject (readonly)

Returns the value of attribute cookies.



14
15
16
# File 'lib/screenplay/actors/api.rb', line 14

def cookies
  @cookies
end

Instance Method Details

#configure(config) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/screenplay/actors/api.rb', line 16

def configure(config)
  @url = config[:url].to_s
  @url += '/' unless @url.end_with?('/')
  @headers = {}
  @config = config
  @cookies = nil
end

#play(params, input) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/screenplay/actors/api.rb', line 24

def play(params, input)
  raise 'Missing configuration api.url' if @url == '/'
  path = params[:path]
  method = params[:method].downcase.to_sym rescue :get
  expects = (params[:expect] || 200).to_i
  data = params[:data] || {} rescue {}
  data = input if (data.is_a?(String)) && (data == '$input')
  data.stringify_keys!
  headers = {}
  headers['Content-Type'] = @config[:content_type] if (!@config[:content_type].nil?)
  headers[:cookie] = @cookies unless @cookies.nil?
  url = @url + path.to_s.replace_vars(input)
  if ([:get, :head, :delete].include?(method))
    headers[:params] = data
    data = {}
  end

  if (headers['Content-Type'] == 'application/json')
    data = JSON.generate(data)
  end

  puts "\nAPI - #{method.to_s.upcase} - #{url}: #{data}" if Screenplay.options[:debug]

  begin
    response = RestClient::Request.execute({
      url: url,
      method: method,
      headers: headers,
      payload: data
    })
  rescue => e
    raise e if e.response.nil?
    response = e.response
  end

  if response.code != expects
    raise WrongResponseCodeException.new(expects, response.code, response.body.to_s)
  end

  unless response.nil?
    output = JSON.parse(response.body) rescue {}
    @cookies = response.headers[:set_cookie][0] rescue nil
  end

  return output || {}
end