On Friday, June 5, 2015 at 4:01:42 AM UTC-7, siva wrote:
>
>
> Hi 
>
> Here is my following code:
>
>
> # app/models/purchase_order.rb
> class PurchaseOrder
>
>   after_create :send_po_by_mail
>
>   def send_po_by_mail
>
>     Thread.new do
>       begin
>         Notifier.generate_po(self).deliver_now
>         self.update_attributes(mail_status: SUCCESS)
>       rescue
>         self.update_attributes(mail_status: FAIL)
>       end 
>     end 
>   end
> end
>
> # spec/models/purchase_order_spec.rb
>
> example "update mail status as 'success' if sent successfully" do
>   allow(Notifier).to receive(:generate_po).and_return(msg = 
> double('ActionMailer::MessageDeliver'))
>   allow(msg).to receive(:deliver_now).and_return(true)
>   po = create(:purchase_order, job: create(:job))
>   
>   expect(po.reload.mail_status).to eq(PurchaseOrder::SUCCESS)
> end 
>
>
>
>
>
> When I ran rspec the above test case is failing. Where I am doing wrong? 
> Could you help me?
>

Threads provide no guarantees about when the OS will schedule them.  When 
you start using threads you need to synchronize at appropriate points if 
you want to assert that the thread completed it's work.  For this kind of 
situation, the standard way to do that is `Thread#join`:

http://ruby-doc.org/core-2.2.0/Thread.html#method-i-join

It will block until the thread is complete, so that have a guarantee that 
the thread's work was finished.

Unfortunately, the thread instance is created in a private method and 
discarded so you don't have direct access to that thread from your spec in 
order to join on it.  You could use `Thread.list` to find that thread:

http://ruby-doc.org/core-2.2.0/Thread.html#method-c-list

...but I'd say that your code isn't very testable, and it's far better to 
use your testing pain as an impetus to improve the design.

Most people do that kind of background work using something like Sidekiq 
rather than a thread:

http://sidekiq.org/

Have you considered using that?

Myron

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rspec/f97c0ee4-371b-41ef-b631-02c338d4f0e5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to