How to visit link in email opened with letter_opener gem - ruby

I am working on some QA automation using Cucumber and Capybara and have a step:
When(/^I follow the reset password link in the email$/) do
last_email = ActionMailer::Base.deliveries.last
password_reset_url = last_email.body.match(/http.*\/users\/password\/edit.*$/)
visit password_reset_url
end
The step fails with:
undefined method `body' for nil:NilClass (NoMethodError)
Additionally, dropping binding.pry after the first line results in nil for last_email which is weird.
Does anyone have advice or thoughts on why that may be happening here?

If you're using letter_opener then emails aren't going to ActionMailer deliveries and are being opened in a browser not controlled by Capybara. If you want to work with emails in capybara you should probably be looking at the capybara-email gem rather than letter_opener. Letter_opener is aimed more at the dev environment rather than test

Tom Walpole's answer is absolutely correct in content and pointing you in the direction of the capybara-email gem.
Here's a potential example of how you could change your code sample, assuming that you have another Cucumber step that has clicked a button/link to send reset password instructions:
When(/^I follow the reset password link in the email (.*)$/) do |email|
# finds the last email sent to the passed in email address.
# This also sets the `current_email` object, which you can think
# of as similar to Capybara's `page` object, but for an email.
open_email(email)
# Assuming the email link to change your password is called
# 'Change my password', you can just click it, just as you would
# on a Capybara `page`.
current_email.click_link 'Change my password'
end
After clicking the link, you will be taken to whatever page where you can continue on to fill_in 'New password', with: 'foobar' etc, which I'm assuming you've got covered in another Cucumber step.

Related

Clicking link with JavaScript in Mechanize

I have this:
<a class="top_level_active" href="javascript:Submit('menu_home')">Account Summary</a>
I want to click that link but I get an error when using link_to.
I've tried:
bot.click(page.link_with(:href => /menu_home/))
bot.click(page.link_with(:class => 'top_level_active'))
bot.click(page.link_with(:href => /Account Summary/))
The error I get is:
NoMethodError: undefined method `[]' for nil:NilClass
That's a javascript link. Mechanize will not be able to click it, since it does not evaluate javascript. Sorry!
Try to find out what happens in your browser when you click that link. Does it create a POST or GET request? What are the parameters that are sent to the server. Once you know that, you can emulate the same action in your Mechanize script. Chrome dev tools / Firebug will help out.
If that doesn't work, try switching to a library that supports javascript evaluation. I've used watir-webdriver to great success, but you could also try out phantomjs, casperjs, pjscrape, or other tools
The first 2 should have worked so try this, print out the hrefs to make sure it's really there:
puts page.links.map(&:href)
Remember that just because you can see it in your browser does not mean it appears in the response. It could have been sent as an ajax update.
Also you can just do this which I think is cleaner:
page.link_with(:href => /menu_home/).click
However I don't think clicking that link will do what you want since it's javascript.
Here's a way to handle it. Assume your page returns this content:
puts page.body
<HTML><SCRIPT LANGUAGE="JavaScript"><!--
top.location="http://www.example.com/pages/myaccount/dashboard.aspx?";
// --></SCRIPT>
<NOSCRIPT>Javascript required.</NOSCRIPT></HTML>
We know it's coming so we know what to check for:
link_search = %r{top.location="([^"]+)"}
js_link = page.body.match(link_search)[1]
page = agent.get(js_link)

Testing Sinatra's redirect back in rspec

I am running a sinatra app and have a testing suite setup using rspec 2.7.0 and webrat 0.7.3 (both the most recent versions). I have an extensive set of tests for all of my request actions and it seems to be working fine. Today I discovered Sinatra's redirect back request-level helper and implemented it in a couple of areas of my application that were rendering forms with get requests which were taking parameters.
The nice thing about the redirect back helper is that if I have an action say:
get '/login' do
#used_var = params[:var]
haml :login
end
Which renders a form, I can have validation on the post request receiving the form:
post '/login' do
# pretend User.authenticate pulls back a user entry from the database if there
# is a valid username/password combination
unless User.authenticate(params[:username], params[:password]).nil?
redirect '/content'
else
flash[:notice] = "Invalid username/password combo"
redirect back # will redirect back to the get '/login' request
end
end
And if the form doesn't validate properly, it will redirect back to the page with the from and retain any parameters that were passed in without me having to worry about storing it to a session variable. The only problem is that rspec doesn't seem to want to play nicely with the redirect back helper. i.e. if I have a spec action that does this:
it 'should redirect to login when invalid username/password combo is received.' do
get '/login', :var => 'value'
fill_in 'username', :with => 'invalid_username'
fill_in 'password', :with => 'invalid_password'
click_button 'Submit'
last_response.should be_redirect; follow_redirect!
last_request.url.should include("/login")
end
The spec fails to pass because for some reason it seems that rspec or webrat isn't picking up on the redirect back helper and is instead redirecting the request back to the root url for my application ('/').
What I want to know is whether there is a way to get rspec to redirect to the proper location in these instances? The actual application functions as expected when I test it with my browser (it redirects me to the first page with parameters), but the rspec tests don't pass properly.
try to pass :referer => '/login' to your requests, so redirect_back can know where the actually 'back' is
Apparently this was a bug in rack, and it appears to have been fixed with the release of rack 1.3.0. I tested this spec with rack 1.2.5 (most recent version prior to 1.3.0 release), and it failed, but upon upgrading to 1.3, it started passing.
After some digging around, pretty sure that this pull request (here is the commit) was the change that fixed it.
So it is no longer an issue in rack ~> 1.3.

Using Cucumber to test controller without a view in Rails

I'm a ruby/rails newbie and the application I'm developing starts with a HTTP post from another website which passes in some data and then displays some data capture screens before calling a web service.
I want to start this project using an outside in approach using Cucumber for integration tests and rspec for functional/unit testing.
Using Cucumber how do I simulate the post from the external website so that I can test the flows with the application.
It doesn't really matter to the application where the call originated; only that the parameters supplied match the expected ones from the referring page. If you depend on a specific HTTP_REFERER being set, check out this answer on how to set a header in Cucumber.
add_headers({'HTTP_REFERER' => 'http://referringsite.com'})
Since you already know which query parameters/headers your app expects from the referring site you can create a setup block that will set these appropriately for each cuke.
If you are using Cucumber with Capybara you can do a HTTP POST like this.
When /^I sign in$/ do
#user = Factory(:user)
get "/login"
page.driver.post sessions_path, :username => #user.username, :password => #user.password
end
Alternatively if you have a view it would be something like this.
When /^I sign in$/ do
#user = Factory(:user)
visit "/login"
fill_in "Username", :with => #user.username
fill_in "Password", :with => #user.password
click_button "Log in"
end

Browser url not returning new url

I am experimenting with using rspec and watir to do some tdd and have come across a problem I can't seem to get past. I want to have watir click a link (target="_blank") and then get the url of the newly loaded page. Watir clicks the link but when I attempt to get the url I receive the old url not the current. Watir docs seem to indicate that the Browser url method will return the current url. I found a blog post that seems to solve this issue by having Watir execute some javascript to get the current url but this isn't working for me. Is there anyway to get the current url from a link click with Watir?
<!-- the html -->
LinkedIn
#The rspec code
it "should load LinkedIn" do
browser.link(:href => "http://www.linkedin.com").click
browser.url.should == "http://www.linkedin.com"
end
The target will load the link in a new browser window, therefore you need to switch to that window to assert the url:
it "should load LinkedIn" do
browser.link(:href => "http://www.linkedin.com").click
browser.window(:title => /.*LinkedIn.*/).use do
browser.url.should == "http://www.linkedin.com"
end
end
See: http://watirwebdriver.com/browser-popups/ for more examples

Login using headers in cucumber

I'm new at cucumber and capybara so maybe this is easy.
I'm using headers to check if a user is logged in or not and i'm having a problem when doing cucumber testing.
I use Capybara and Cucumber and a "add headers hack": http://aflatter.de/2010/06/testing-headers-and-ssl-with-cucumber-and-capybara/
The problem I have is that it only sets the header once in each feature story. So if I have a story that goes trough more than one step the header is gone and the user is no longer logged in.
An example story:
Given I am logged in as a superuser
And I have a database "23456789" that is not active
And I am on the home page
When I follow the "Delete" link for "23456789.sqlite"
Then I should see "Deleted the database"
In this story the "When I follow the "Delete" link for "23456789.sqlite" line will not work since the user is no longer logged in!
Have thought about using session or the before/after in cucumber.
Does someone have a clue on how to fix this?
You can achieve this by passing the username in an environment variable:
When /^I am logged in as a superuser$/ do
ENV['RAILS_TEST_CURRENT_USER'] = 'admin'
end
application_controller.rb:
before_filter :stub_current_user
def stub_current_user
if Rails.env == 'cucumber' || Rails.env == 'test'
if username = ENV['RAILS_TEST_CURRENT_USER']
#current_user = User.find_by_username(username)
end
end
end

Resources