Matthew tells the story of Jesus's birth from Joseph's point of view. Imagine learning that your fiancée is pregnant, and you know you aren't the father! What would you do?
First century Jewish men had the legal right to have their unfaithful wives or brides-to-be stoned to death--what is known as "honor killing" today. Matthew tells us that Joseph was a just man, however, so he planned to end the relationship discreetly. Apparently, justice has something to do with foregoing one's legal rights or cultural privileges in the interest of showing mercy.
But in a dream, an angel of the Lord called Joseph to an even higher righteousness: marry the woman who, in the eyes of society, had dishonored him. The angel lets Joseph (and us) in on a secret. His fiancée had not been unfaithful; her pregnancy was an act of God. Did anyone else know? Would they believe Mary and Joseph if they told them?
There's what's legal; then there's what's merciful, but finally, there is God's will. Choosing God's will often means setting aside our fears about what the neighbors will think.
The dream came "just when (Joseph) had decided" to break the engagement. Good decision-makers are willing to set aside their best decisions, even at the last minute, for the sake of the divine will. And good decision-makers are open to influences that are not strictly rational. Joseph did not go through with the marriage because that's what the cost-benefit analysis recommended, but because he dreamed that God told him to!
A lot of coaches and career planners and Facebook memes will tell you, "Pursue your dreams." "Be a stepfather to God's son" was not Joseph's dream; it was God's dream for him. Joseph pursued it anyway, and the world was changed.