Mock/stub perishable_token or register_url with Authlogic

19 views
Skip to first unread message

Ester Ytterbrink

unread,
Dec 12, 2014, 7:03:28 AM12/12/14
to rs...@googlegroups.com
Hi!
I want to write an accept test for our user account activation emails, that is to have a plain txt file with the email is properly formatted with all the test data in place and then maka a diff with the email produced by the code. 

My problem is that authlogic renders a perishable_token for the user that is random (very good in production, not so much in tests), that I can't seem to mock. In the Mailer object i have @activate_account_link = register_url(@user.perishable_token) and for my tests I want @activate_account_link to be deterministic. 

I have tried allow().to and let, but I am new to this, and I can not make them work. As for now I have monkey patched register_url to be overloaded in my mailer object (it is part of Authlogic) for the tests, but it does not feel right. 

Has anyone any experience with testing things like this?

What type of mocking/stubing is the correct approach?

Thank you beforehand. 
Ester Ytterbrink


Myron Marston

unread,
Dec 12, 2014, 11:56:15 AM12/12/14
to rs...@googlegroups.com

The tricky thing about register_url(@user.perishable_token) is that the receiver is self (in whatever context this is taken from) and without seeing the fuller context to know what self is there, I can’t provide an exact snippet that will work to stub that. If it’s an object that you don’t have a reference to in your test (e.g. because rails instantiates it for you) then you’re going to have even more difficulty stubbing it.

Instead, my recommendation is to put this logic behind and interface; the you can define a second, polymorphic implementation of it for your test environment. Something like:

# in lib/account_activation_link_generator.rb or similar
class AccountActivationLinkGenerator
  include Rails.application.routes.url_helpers

  def generate_for(user)
    register_url(user.perishable_token)
  end
end
# in config/application.rb:

require 'account_activation_link_generator'
config.account_activation_link_generator = AccountActivationLinkGenerator.new
# in spec/rails_helper.rb or spec/spec_helper.rb (depending on your test env setup)
class TestAccountActivationLinkGenerator
  def generate_for(user)
    # return a static url for your test environment
  end
end

Rails.application.config.account_activation_link_generator = TestAccountActivationLinkGenerator.new
I haven't tested this and I haven't done rails in years so there may be something there that's not quite right but hopefully you get the idea.

HTH,
Myron 
Reply all
Reply to author
Forward
0 new messages