On Friday, December 12, 2014 4:03:28 AM UTC-8, Ester Ytterbrink wrote:
>
> 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
>

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 similarclass 
AccountActivationLinkGenerator
  include Rails.application.routes.url_helpers

  def generate_for(user)
    register_url(user.perishable_token)
  endend

# 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
  endend
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 

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rspec/baa4d9ef-99d6-4d62-ac84-36897e163be1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to