Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to test PublishSubject in RxSwift #218

onmyway133 opened this issue Apr 29, 2019 · 0 comments


None yet
1 participant
Copy link

commented Apr 29, 2019

Use homemade Recorder

class Recorder<T> {
    var items = [T]()
    let bag = DisposeBag()

    func on(arraySubject: PublishSubject<[T]>) {
        arraySubject.subscribe(onNext: { value in
            self.items = value
        }).disposed(by: bag)

    func on(valueSubject: PublishSubject<T>) {
        valueSubject.subscribe(onNext: { value in
        }).disposed(by: bag)

Then test

final class BookViewModelTests: XCTestCase {
    func testBooks() throws {
        let expectation = self.expectation(description: #function)
        let recorder = Recorder<Book>()
        let viewModel = BookViewModel(bookClient: MockBookClient())
        recorder.on(arraySubject: viewModel.books)

        DispatchQueue.main.asyncAfter(deadline: + 0.5, execute: {

        wait(for: [expectation], timeout: 2)
        XCTAssertEqual(recorder.items.count, 3)

Need to use great timeout value as DispatchQueue is not guaranteed to be precise, a block needs to wait for the queue to be empty before it can be executed

Make expectation less cumbersome

extension XCTestCase {
    func waitOrFail(timeout: TimeInterval) {
        let expectation = self.expectation(description: #function)

        DispatchQueue.main.asyncAfter(deadline: + timeout, execute: {

        wait(for: [expectation], timeout: timeout + 2)

@onmyway133 onmyway133 referenced this issue May 14, 2019


Writing #165

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.