A large part of the history of both of them resides in a contest for the whole peninsula. Portugal started out as a vassal to the Emperor Alfonso VII of Leon (1105-1157), and its independence (1143) was dearly purchased, involving both wars and a bribe to the Pope consisting of many pounds in silver bullion in exchange for the transference of the feudal oath of the Portuguese King to the Pope in Rome instead of the Emperor in Spain. At various moments in Portuguese History Portuguese kings tried to acquire some or all of the thrones of Spain (remember that Spain itself is a collection of several kingdoms), sometimes by war (as in the War of Castillian succession from 1475-79), sometimes by marriage (like the tragic events surrounding Miguel of Portugal (d.1500), who, if he hadn't died in infancy, would have inherited the royal crowns of Portugal, Castille, and Aragon, being heir apparent to all of them by virtue of being the grandson of Isabella of Castille and Fernando of Aragon, and son of Manuel of Portugal).
At one point the issue was indeed resolved, with the throne of Portugal being inherited at the tip of the sword in 1580 by Phillip II of Spain (Phillip I by Portuguese reckoning), who took over the country after the collapse of the Portuguese regime following the military disaster spearheaded by King Sebastian (d.1558). This led to an united peninsula under one king; it goes by the name of the Iberian Union and it lasted 60 years and was ruled by three different kings. If the rebellion to restore Portuguese independence (1640) had been squashed like similar rebellions were squashed elsewhere (like in Catalonia), Portugal would now be simply another kingdom in a greater Hispania, much like Aragon or Navarra.
In fact, interests in one country for the other, while bilateral in the Medieval period, become more one-sided the more Spanish power grows when compared to Portugal's. There are further clashes, especially during the Napoleonic era (leading to a still unresolved, though largely dormant issue concerning a few border towns, notably Olivença), and then particularly and most interestingly a secret plan between Franco and Hitler, which would have seen Franco's Spain join WWII on the Axis side in exchange, among other things, for Portugal.