advantage of tap method in ruby

后端 未结 19 1004
天命终不由人
天命终不由人 2020-12-22 16:50

I was just reading a blog article and noticed that the author used tap in a snippet something like:

user = User.new.tap do |u|
  u.username = \         


        
相关标签:
19条回答
  • 2020-12-22 17:56

    Apart from the above answers, I have used tap in stubbing and mocking while writing RSpecs.

    Scenario: When I have a complex query to stub and mock with multiple arguments which shouldn't go missed. The alternative here is to use receive_message_chain (but it lacks the details).

    # Query
    Product
      .joins(:bill)
      .where("products.availability = ?", 1)
      .where("bills.status = ?", "paid")
      .select("products.id", "bills.amount")
      .first
    
    # RSpecs
    
    product_double = double('product')
    
    expect(Product).to receive(:joins).with(:bill).and_return(product_double.tap do |product_scope|
      expect(product_scope).to receive(:where).with("products.availability = ?", 1).and_return(product_scope)
      expect(product_scope).to receive(:where).with("bills.status = ?", "paid").and_return(product_scope)
      expect(product_scope).to receive(:select).with("products.id", "bills.amount").and_return(product_scope)
      expect(product_scope).to receive(:first).and_return({ id: 1, amount: 100 })
    end)
    
    # Alternative way by using `receive_message_chain`
    expect(Product).to receive_message_chain(:joins, :where, :where, :select).and_return({ id: 1, amount: 100 })
    
    0 讨论(0)
提交回复
热议问题