← Back to Upcase

Testing monban with factory_girl - what is the best way?


(Patrik Bóna) #1

Hello Guys,

I am struggling with some tests for monban authentication.

I want to create users with factory girl:

FactoryGirl.define do
  factory :user do
    username 'Joe'
    password 'password'
  end
end

But it is not working out of the box, because of missing password= method in User model.

I see two solutions and I do not know decide which is better/worse. Maybe it should be done in completely different way, but I do not know how.

Solution 1: Create password= method directly in User model.

This is what came to my mind as first. And it was working. Factory girl did it’s job and tests were passing.

But is it good idea to create new method for Class just because of tests? Isn’t it useless?

Solution 2: Monkey patch User model with password= just in test environment.

So later I’ve started to think that it is stupid to add some functionality which is needed just in tests, so I’ve monkey patched User class just in test environment. Oh god I was so proud that I’ve come with this solution.

But wait! I’ve modified Class just in my test environment so my tests are passing, which is good. But how can be I sure that there are no issues in production environment?

So… could you please advise me which way is better? Or how to do it in correct way? Because right now I am really lost.

Many thanks for your answers!

p.s. this is my implementation of password= method:

def password=(password)
  self.password_digest = Monban.encrypt_token(password)
end

(Matthew Mongeau) #2

@patrikbona the way I intended this to be done was like so

 FactoryGirl.define do
  factory :user do
    username 'Joe'
    password_digest 'password'
  end
 end

Then in a support file for you testing framework override the following like so:

Monban.config.encryption_method = -> (password) { password }
Monban.config.token_comparison = -> (digest, unencrypted_password) { digest == unencrypted_password }

In the future this will probably just work with a call to:

Monban.test_mode

But that isn’t implemented yet.

As an aside, this is actually much faster then hitting BCrypt in your tests and easier than overriding BCrypt’s minimum runs.


(Patrik Bóna) #3

@halogenandtoast thank you very much for your answer, I will update my tests.