1

I have a ControlProperty binding like this in my UIViewController:

textView.rx.text.orEmpty.asObservable()
    .bind(to: viewModel.descriptions)
    .disposed(by: disposeBag)

, where viewModel.descriptions is of type BehaviorRelay<String>.

In a TDD approach, I would like to write an (initially failing) test (as the initial step of the red-green-refactor cycle) to see that this binding exists. I tried with a test code like this:

sut.textView.insertText("DESC")
sut.textView.delegate?.textViewDidChange?(sut.textView)

expect(mockViewModel.lastDescriptions).to(equal("DESC"))

, where sut is my ViewController and mockViewModel contains code to subscribe to the descriptions BehaviorRelay:

class MockViewModel: MyViewModelProtocol {
    var descriptions = BehaviorRelay<String>(value: "")
    var lastDescriptions: String?
    private var disposeBag = DisposeBag()

    init() {            
        descriptions.asObservable()
            .skip(1)
            .subscribe(onNext: { [weak self] (title: String) in
                self?.lastDescriptions = title
            })
            .disposed(by: disposeBag)
    }
}

However, I cannot push the new value to the textView so that the descriptions BehaviorRelay gets it.

How can I achieve descriptions.asObservable() to fire when entering a value in the textView? If it were a UITextField then I would do:

textField.text = "DESC"
textField.sendActions((for: .editingChanged))

Thanks in advance for any help.

rgal75
  • 151
  • 6
  • IMHO there is nothing to test in that binding. Only test the dynamic behavior _you_ wrote. If you *really* feel the need, the only test that makes sense is to ensure that the code exists and that's it. You could do that using a regex on the file itself. – Daniel T. Oct 03 '18 at 10:52
  • There may be additional RX operators before .bind and thats logic to test. (I tried to simplify the code above to reduce noise and focus on the problem.) – rgal75 Oct 03 '18 at 14:01
  • Then that logic should go into your ViewModel and you test that feeding data to it results in whatever it should. But you don't test the binding itself. RxSwift is in itself unit tested ! – Valérian Oct 03 '18 at 16:04
  • I do not want to test the binding itself. I am following a TDD approach and the "red" part of the red-green-refactor cycle when connecting the UITextView to the view-model is to write a test that such a binding exists. – rgal75 Oct 05 '18 at 05:20
  • That's fine, write the test if you feel you must, but the test needs to prove the correct thing. The question you are trying to answer with the test is "Is `textView` bound to `descriptions`?" You aren't testing behavior here, just whether or not the code exists. You can test existence by just loading the .swift file and running a regex over it. – Daniel T. Oct 05 '18 at 13:05

0 Answers0