ENV["LIFEPEX_ENV"] = "test" require "yaml" require_relative "./fixtures_reader" require_relative "../src/app" require "rack/test" require "test/unit" class LifePexTest < Test::Unit::TestCase include Rack::Test::Methods def app LifePex::App end %i(get head).each do |verb| define_method "api_#{verb}" do |uri, **headers| self.send(verb, uri, headers.merge({ "CONTENT_TYPE" => "application/json" })) end end %i(post put patch delete).each do |verb| define_method "api_#{verb}" do |uri, body = {}, **headers| header "Accept", "application/json" header "Content-Type", "application/json" self.send(verb, uri, body.to_json, headers.merge({ "CONTENT_TYPE" => "application/json", })) end end def login_as(username = "test", password = "test") api_post '/api/user/v1/login', { username: username, password: password } end # check if every key of `minimal_data` is contained in `full_data` def assert_hash_include(minimal_data, full_data) full_data = full_data.stringify_keys minimal_data.stringify_keys.each do |key, value| assert_equal value, full_data[key], "#{key} should contains <#{value}>, got <#{full_data[key]}>" end end # parse the body as a json def api_reponse_body JSON.parse last_response.body end # check if the body contains a message def assert_message_exist assert_not_empty api_reponse_body.dig "message" end # check if the entity.user_id belongs to the user who sent the last req def assert_entity_owned(entity) user_id = JWT.decode(last_request.cookies["auth"], nil, false).first["user_id"] assert_equal user_id.to_s, entity["user_id"].to_s end # status may be a Regexp: the assertion with test if they match # status may be a String: the assertion with test if the param includes the response status # status may be another thing: the assertion with test equality def assert_status(status) if status.is_a?(Regexp) assert_match status, last_response.status.to_s elsif status.is_a?(String) assert_equal status, last_response.status.to_s[0..(status.size)] else assert_equal status, last_response.status end end def assert_client_error(status = /^4\d\d/) refute last_response.ok? assert_status status end def assert_server_error(status = /^5\d\d/) refute last_response.ok? assert_status status end end