Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable auto-complete when running Xcode UI Tests?

As part of my UI Tests, I'm generating a random string as titles for my objects. The problem is that when this title is input via a keyboard (using XCUIElement.typeText()), iOS sometimes accepts an auto-suggested value instead.

For example, I may want it to type an auto generated string of "calg", but auto correct will choose "calf" instead. When I try to look for this value later on with an assertion, it doesn't exist and fails incorrectly.

Is there a way to tell the UI tests that they shouldn't be using auto correct, or are there an workarounds I can use?

like image 810
Senseful Avatar asked Oct 01 '15 23:10

Senseful


2 Answers

Unless you need auto-suggest for any test scenarios, did you try turning off auto-correction in device/simulator settings.

Settings-> General -> Keyboard -> Auto-Correction

like image 140
Sushant Avatar answered Nov 01 '22 10:11

Sushant


I don't believe you can turn off auto-correction through code from your UI Testing target.

You can, however, turn it off for the individual text view from your production code. To make sure auto-correction is still on when running and shipping the app, one solution would be to subclass UITextField and switch on an environment variable.

First set up your UI Test to set the launchEnvironment property on XCUIApplication.

class UITests: XCTestCase {
    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app.launchEnvironment = ["AutoCorrection": "Disabled"]
        app.launch()
    }

    func testAutoCorrection() {
        app.textFields.element.tap()
        // type your text
    }
}

Then subclass (and use) UITextField to look for this value in the process's environment dictionary. If it's set, turn auto-correction off. If not, just call through to super.

class TestableTextField: UITextField {
    override var autocorrectionType: UITextAutocorrectionType {
        get {
            if NSProcessInfo.processInfo().environment["AutoCorrection"] == "Disabled" {
                return UITextAutocorrectionType.No
            } else {
                return super.autocorrectionType
            }
        }
        set {
            super.autocorrectionType = newValue
        }
    }
}
like image 32
Joe Masilotti Avatar answered Nov 01 '22 10:11

Joe Masilotti