Here's how I go about it, and I have a few methods :)
First and most common way for me
1. I'm fiddling around on my guitar or piano, maybe I'm even just writing a poem when something pops into my head.
2. I attempt to figure it out and write it down
3. Determine the key signature so that you can have guidelines of notes or guidelines of modulations to write on
4. Fill in the others parts
The second way
1. I'll be methodically trying to come up with something in music that hasn't been done before when I come up with something that sounds new and interesting. This involves taking a lot of scales and or intervals that I like then figuring out how to smash them together.
2. Determine the key or multiple keys and figure out what can be played over where
3. Fill in remaining parts
The idea here is that while some people can just write music, I find theory makes everything faster and easier. Having theory behind it gives you guidelines, and people who write by ear almost always end up falling behind theory. It's a way to speed up the process a ton :) If you aren't too familiar with it, read up on the modes and chord progressions :)