Rajoy had asked to testify by videoconference but the court ruled he must appear in person to answer questions.
He will testify at a court in San Fernando de Henares near Madrid on July 26th.
The so-called Gurtel trial centres on a vast kickbacks scheme that allegedly helped finance his Popular Party (PP), which today has been weakened by repeated accusations of graft.
- Spain urgently needs to deal with systematic corruption
- Ten Spanish corruption scandals that will take your breath away
- Justice for all? Spanish lessons on corruption and draining the swamp
While Spain's 62-year-old leader is not accused of anything, his post as party chief since 2004 means he could provide valuable testimony.
Rajoy will become the first acting prime minister to appear in court as a witness since Spain's transition to democracy following dictator Francisco Franco's death in 1975.
Two former prime ministers – Felipe Gonzalez, an ex-Socialist leader, and Adolfo Suarez, prime minister during the transition – appeared in court in separate trials in 1998 after they were no longer in office.
The court said in its ruling that Rajoy will take the stand “not as the head of the government, but as a Spanish citizen in the capacity of a witness” because “of the roles he held in the PP”.
It said it would take “all necessary measures to protect his institutional image”, without providing details.
“I am available for whatever the courts decide,” Rajoy told a news conference in Portugal when asked about the ruling.
The Gurtel case allegedly saw companies shower former PP lawmakers and civil servants with bribes in exchange for contracts.
Altogether, 37 defendants face justice including two former party treasurers and businessman Francisco Correa, the alleged head of the network.
According to a confession published by Correa in online daily eldiario.es, companies would give him a commission of two to three percent on the value of public contracts.
After taking his share, he would allegedly give politicians involved in awarding contracts some of the money too.
He also claimed he gave money to Luis Barcenas, the PP's manager and treasurer from the 1980s until 2009.
The fund is an ingredient of the current case but not the focus, as a separate trial on it is pending.
Corruption is a major issue in Spain – which last year scored its worst ranking in Transparency International's annual corruption perceptions index – with the PP, rival Socialists and regional politicians hit by scandals.
Such is public anger over the issue that many voters have flocked to two relatively new parties — the far-left Podemos and the centre-right Ciudadanos.