This blog outlines how to do scripting for test cases that involve editing of word documents or verification of the contents of a word document.
The script would need to have:
1 |
require 'win32ole' |
To open an MS word document:
1 2 |
@word = WIN32OLE.new('Word.Application') document = @word.Documents.Open('C:HelloWorld.docx') |
The Range(x,y) specifies the place at which text will be inserted. “.Text” allows to insert text in the word document at the location specified by parameters x and y. Here we insert text “Hello World!!!” at the beginning of the document.
1 |
document.Range(0, 0).Text = "Hello World!!!" |
Once the document is edited, it should be saved before closing. So, just use “.save()” or “.saveas()” to save the document.
1 2 3 |
@word.documents.save() @word.documents.close() @word.Quit |
This was all about editing a word document. Now, we will validate the changes in the document. So, for validating open the document again. Capture all the text of the word document in a variable (filetextall). Check whether the selection includes the text you are looking for (“Hello World!!!” in this case):
1 2 3 4 5 6 7 8 9 |
@word.selection.wholestory filetextall = @word.selection.text if filetextall.include?('Hello World!!!') puts("Found string in body of word document") else puts("Did not find string in body of word document") end @word.documents.close() @word.Quit |
We can easily manipulate this code to create a new instead of opening an existing document.
All we need to do is:
Replace:
1 |
document = @word.Documents.Open('C:HelloWorld.docx') |
With:
1 |
document = @word.Documents.Add |
Just remember one thing, there should be no instance of word already open on your system (Check task manager to ensure that no Winword.exe is running). I noticed that in case an instance is already open, the command documents.open() throws error.
Happy Scripting!!!