highfidelity/fake_braintree

Best practice for creating a customer to use for each test using Rails4 / RSpec

Closed this issue · 2 comments

I'm using Rails 4 and RSpec, and I'm trying testing a controller that adds, removes, and sets the default payment method. In order for any of that to work, I need a braintree customer to be created first.

I guess my question is, has anyone dealt with this before that could recommend a best practice? Should I be creating a customer in a before each block for every test I run for that controller? Or could I abstract that to only happen once per controller, like with a let statement? I'm using factory girl to use factories in my let statements.

What I ended up doing was using this code in account.rb:

def create_braintree_customer
  result = Braintree::Customer.create(
    first_name: owner.first_name,
    last_name: owner.last_name,
    company: company_name,
    email: owner.email,
    phone: (owner.phone unless owner.phone.blank?)
  )
  self.update(braintree_customer_id: result.customer.id)
end

Then I call that in my accounts controller:

if @account.save
  @account.create_braintree_customer
  ..

I would use a callback, but I don't want that running on every test that uses an account.

Then in my controller specs that rely on a customer being created already (like my credit card controller), I use:

before do
  login(owner)
  account.create_braintree_customer
end

And I'm good to go. Thanks again @wacii for pointing me in the right direction of looking at the specs in this library. It helped everything make sense to me.

And, I also realize now that I don't necessarily need a customer to create a payment method (specs prove that), but I am setting the customer before all my actions in the credit card controller, so I needed one for the before_action to pass.

Hopefully this helps someone, and any thoughts on this strategy are welcome.