← Back to Upcase

Testing Push Class


(charlieanna) #1

Is this the right way to test this class? And is this way the right way to write the class?

require "spec_helper"

describe Push do
	
        push = Push.new([],"")
        subject{push}
	it{should respond_to(:push)}
	it{should respond_to(:create_push)}
	it{should respond_to(:send_push)}

	it "#send_push" do
          resp = push.send_push({})
		
          expect(resp).to eq "200"
	end

	it "create_push" do
	  resp = push.create_push
          puts resp
          expect(resp).to eq({"push"=>{"devices"=>[], "message"=>""}})
	end

	it "#push" do
          resp = push.push
          expect(resp).to be_true
	end
end

This is my file push.rb

def push

  hash = create_push

  resp = send_push hash

  return hash && resp
 
end


def create_push
  timetable_hash = {}
  entries_hash = {}
  entries_hash["devices"] = @devices
  entries_hash["message"] = @message
  timetable_hash["push"] = entries_hash
  return timetable_hash
end

def send_push(hash)
  uri = URI('http://0.0.0.0:3000/push/push1')


  headers = { "Content-Type" => "application/json"}
                http = Net::HTTP.new(uri.host, uri.port)


                           resp, dat = http.post(uri.path, hash.to_json, headers)

return resp.code
  
end

end

And this is how I call this class.

devices = ['registration_id1',registration_id2]     
message = 'http://idlecampus.com/groups/'+params['timetable']["group"]["group_code"]+'/timetable.json'
            
Push.new(devices,message).push

(Ben Orenstein) #2

Well, there is no “right” way to test or write a class. Just lots of options with different pros and cons.

Here are a few notes though

  • You’re not really testing that send_push posts to that uri. You might want to investigate the fake_web gem.
  • I’d create a Push instance that actually has devices and message data in it so you can test a more complete return value from create_push.

(Ben Orenstein) #3

Also, I structure my tests like this:

describe Class do
  describe "#method_name" do
    it "returns bar" do
      expect(Class.method_name).to eq :bar 
    end
  end
end