The modern country of Spain was formed in the wake of the expansion of the Christian states in northern Spain, a process known as the Reconquista. The Reconquista spanned approximately 770 years between the Battle of Covadonga c. 720 CE and the Fall of Granada in 1492.
Several independent Christian kingdoms and mostly independent political entities (Asturias, León, Galicia, Castile, Navarre, Aragon, Catalonia) were formed by their own inhabitants' efforts under aristocratic leadership, coexisting with the Muslim Iberian states and having their own identities and borders.
Eventually, the kingdoms of Castile and Aragon eclipsed the others in power and size through conquest and dynastic inheritance, their Crowns ultimately merging in 1469 with the marriage of the Catholic Monarchs. After this, the Muslim Kingdom of Granada was conquered in 1492, and Navarre invaded and forced into the union in 1512, through a combination of conquest and collaboration of the local elites.
Portugal, formerly part of León, gained independence in 1128 after a split in the inheritance of the daughters of Alfonso VI and remained independent throughout the Reconquista.
For a short time starting with Philip II of the House of Habsburg, Portugal was united with all the other realms under the same Head of State, in the Iberian Union. However the Portuguese revolted as the Dutch provinces and other Habsburg dominions and became officially independent again from their Sovereigns in 1640.