lundi 23 octobre 2017

When using factory_bot (formerly factory_girl) with RSpec to test in Rails, undefined method "first"

I have an RSpec test that uses factory_bot to create instances. The test passes except when the "first" method is used in a view.

This is the code being tested:

def order_confirm_email(id, items, order, address, coupon)
    @user = User.find(id)
    @items = items
    @order = order
    @address = address
    if coupon == nil
      @coupon = ''
    else
      @coupon = coupon.discount
    end

    mail(to: @user.email, subject: 'Order completed')
  end

This is the test:

it 'sends an email upon checkout process completion' do
      user    = create(:user)
      items   = create(:base_item)
      order   = create(:base_item)
      address = create(:address)
      coupon  = create(:coupon)

      expect(orderConfirmationMail.subject).to eq('Order completed')
    end

So far so good. But when one of the views attempts to access the first instance, as below:

<h1>Order id - <%= @order.first.id %></h1>

Then I receive the following error:

Failures:

  1) UserMailer user_emails sends an email upon checkout process completion
     Failure/Error: <!-- <h1>Order id - <%= @order.first.id %></h1> -->

     ActionView::Template::Error:
       undefined method `first' for 3:Fixnum

According to my understanding, the instances should be persisting since I use create instead of build. But apparently that is not happening. Changing the view is not an option except as a last resort. How do I resolve this?

Aucun commentaire:

Enregistrer un commentaire