Domanda

I am trying to test a thread. Assume that customer, venue, message are all in the above code, but it would be very long to post. I am trying to test the "message" variable, but since it is not an instance variable and it is within a thread I am not able to test it very easily. I am assuming that stubbing the thread would be the correct route to test this with rspec, but if you have any other suggestions on how to accurately test the "message" variable that would be very helpful. Here is a basic version of what I am doing:

Class Messages
  def order_now
    conf = venue.confirmation_message
    message = "Hi #{customer.first_name}, "
    if conf && conf.present?
      message << conf
    else
      message << "your order has been received and will be ready shortly."
    end

    Thread.new do
      ActiveRecord::Base.connection_pool.with_connection do
        Conversation.start(customer, venue, message, {:from_system => true})
      end
      ActiveRecord::Base.connection_pool.clear_stale_cached_connections!
    end         
  end
end

Thank you in advance!

È stato utile?

Soluzione

You're going to have to get a little clever here:

it "should test the conversation message" do
  Conversation.should_receive(:start).with(
    instance_of(Customer), 
    instance_of(Venue),
    "your order has been received and will be ready shortly.",
    {:from_system => true}
  ).and_call_original

  message_instance.order_now.join
end

Basically, you can test that you call your Conversation::start with the right parameters. However, there's a subtlety here - you call message_instance.order_now.join, because order_now returns the thread, and you want to wait for the thread to finish running before your rspec example finishes. #join will block execution of the main thread until the referenced thread finishes running. Otherwise, it would be possible for the rspec example to finish running before the thread executes, resulting in a test failure.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top