title: Unit testing with Realm in iOS
body: <p>I followed the guide on Realm's website, but my test are still producing varying results, depending on the random order they are done.</p>
  
  <p>Either they succeed when run individually, or fail because the data was already set. For example:</p>
  
  <pre><code>XCTAssert(observer.events[0].value.element == "", "Initail hub name is expected to be equal to be an empty string but was \(String(describing: observer.events[0].value.element))")
  XCTAssert(observer.events[1].value.element == testHubName, "Initail hub name is expected to be equal to be the name we set but was \(String(describing: observer.events[1].value.element))")
  </code></pre>
  
  <p>In this example, <code>event[0]</code> is already set to <code>testHubName</code>.
  Or it gets a <code>@throw RLMException(@"Object has been deleted or invalidated.");</code><br>
  So I guess there is some kind race going around, but this is in my <code>setup</code> method:</p>
  
  <pre><code>func setupRealm() {
      testRealm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "DORSessionViewModelTestsRealm"))
      try! self.testRealm.write {
          self.testRealm.deleteAll()
      }
  }
  </code></pre>
  
  <p>So as far as I understand I should have a fresh Realm for every test, so where is the race going on?</p>
  
  <p>Edit: 
  Adding a bigger part of the class</p>
  
  <pre><code>class DORSessionViewModelTests: XCTestCase {
  
  var disposeBag: DisposeBag = DisposeBag()
  var scheduler = TestScheduler(initialClock: 0)
  var testRealm: Realm!
  
  
  override func setUp() {
  
      super.setUp()
      setupRealm()
      setupRx()
  }
  
  
  override func tearDown() {
      super.tearDown()
  }
  
  func testHubNameLabelTextUpdate() {
      let expectation = self.expectation(description: "expect hub name text to update")
      let testHubName = "testHubName"
      let viewModel = getSessionViewModel()
  
      let observer = scheduler.createObserver(String.self)
      scheduler.start()
      let hubNameDriver = viewModel.hubNameLabelText()
      hubNameDriver.asObservable().subscribe(observer).disposed(by: disposeBag)
      hubNameDriver.asObservable().skip(1).subscribeNext { _ in expectation.fulfill()}.disposed(by: disposeBag)
  
      try! self.testRealm.write {
          viewModel.dependencies..hub.name = testHubName
      }
  
  
      waitForExpectations(timeout: 5, handler: { error in
          XCTAssert(observer.events[0].value.element == "", "Initail hub name is expected to be equal to be an empty string but was \(String(describing: observer.events[0].value.element))")
          XCTAssert(observer.events[1].value.element == testHubName, "Initail hub name is expected to be equal to be the name we set but was \(String(describing: observer.events[1].value.element))")
      })
  }
  
  func setupRx() {
      disposeBag = DisposeBag()
      scheduler = TestScheduler(initialClock: 0)
  }
  </code></pre>