Yes pepper spray will stop a dog attack if you're close enough to get the pepper spray into the dogs face and eyes.
The pepper spray will make it very uncomfortable for the dog and burn their eyes and so they will stop attacking or trying to attack and leave you alone.
The dogs eyes can feel the same pain from the pepper spray as humans and spraying them with pepper spray will usually send them running or at least disabled them enough for you to get away from the dog.
I always carry pepper spray and had to use it before on a mean dog that was trying to attack me and it did stop him from attacking.
Having pepper spray is a very good defense item to have with you that is non lethal and can stop attacks from dogs and humans.