I didn't manage to use valgrind, because it never crashes when I'm using valgrind… And also valgrind complains that "Support on MacOS 10.8 is experimental and mostly broken."
Thread 4 Crashed:
0 libsystem_kernel.dylib 0x00007fff841d2212 __pthread_kill + 10
1 libsystem_c.dylib 0x00007fff87494b24 pthread_kill + 90
2 libsystem_c.dylib 0x00007fff874d8f61 abort + 143
3 libruby.2.0.0.dylib 0x000000010c641768 rb_bug + 184
4 libruby.2.0.0.dylib 0x000000010c6f8470 sigsegv + 144 (signal.c:616)
5 libsystem_c.dylib 0x00007fff8748190a _sigtramp + 26
6 libcrypto.0.9.8.dylib 0x00007fff883d6b9e ASN1_STRING_free + 14
7 libcrypto.0.9.8.dylib 0x00007fff883d92a5 ASN1_primitive_free + 85
8 libcrypto.0.9.8.dylib 0x00007fff883d923d ASN1_template_free + 141
9 libcrypto.0.9.8.dylib 0x00007fff883d911b asn1_item_combine_free + 491
10 libcrypto.0.9.8.dylib 0x00007fff883d8f27 ASN1_item_free + 23
11 libssl.0.9.8.dylib 0x00007fff81714bf9 SSL_CTX_use_certificate_chain_file + 457
12 libpq.dylib 0x000000010ca9bc12 pqsecure_open_client + 578
13 libpq.dylib 0x000000010ca8d7e4 PQconnectPoll + 1060
14 libpq.dylib 0x000000010ca8e867 connectDBComplete + 135
15 libpq.dylib 0x000000010ca8f377 PQconnectdb + 39
16 pg_ext.bundle 0x000000010ca68811 gvl_PQconnectdb_skeleton + 17 (gvl_wrappers.c:9)
17 libruby.2.0.0.dylib 0x000000010c773677 rb_thread_call_without_gvl + 87 (thread.c:1217)
18 pg_ext.bundle 0x000000010ca687ed gvl_PQconnectdb + 45 (gvl_wrappers.c:10)
19 pg_ext.bundle 0x000000010ca6b989 pgconn_init + 105 (pg_connection.c:189)
20 libruby.2.0.0.dylib 0x000000010c7689b1 vm_call0_body + 2033 (.vm_eval.c:117)
21 libruby.2.0.0.dylib 0x000000010c767eb0 rb_call0 + 416 (.vm_eval.c:325)
22 libruby.2.0.0.dylib 0x000000010c693819 rb_class_new_instance + 41 (object.c:1763)
23 libruby.2.0.0.dylib 0x000000010c76b7e1 vm_call_cfunc + 1057 (.vm_insnhelper.c:1469)
24 libruby.2.0.0.dylib 0x000000010c7559f5 vm_exec_core + 10885 (insns.def:1002)
25 libruby.2.0.0.dylib 0x000000010c7622b5 vm_exec + 133 (vm.c:1201)
26 libruby.2.0.0.dylib 0x000000010c766423 invoke_block_from_c + 1171 (vm.c:653)
27 libruby.2.0.0.dylib 0x000000010c7615bb vm_invoke_proc + 171 (vm.c:699)
28 libruby.2.0.0.dylib 0x000000010c761500 rb_vm_invoke_proc + 32 (vm.c:715)
29 libruby.2.0.0.dylib 0x000000010c779eca thread_start_func_2 + 522 (thread.c:512)
30 libruby.2.0.0.dylib 0x000000010c779ca5 thread_start_func_1 + 149 (.thread_pthread.c:765)
31 libsystem_c.dylib 0x00007fff87493772 _pthread_start + 327
32 libsystem_c.dylib 0x00007fff874801a1 thread_start + 13
This crash actually never happens when I run the test code within "rails console" (and also it never happens in the actual rails application), it only happens when I run it separately with something like "ruby cancel_test.rb". I was assuming that maybe it is some kind of premature garbage collection, but I cannot see how could that be in this case.