Using Cucumber to test controller without a view in Rails - ruby

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

Related

Adding custom form actions in ActiveAdmin

I'm using ActiveAdmin to add google OAuth credentials to a record. The client ID and Client Secret are added via record/1/edit, and I use those to generate a link to allow access. This link appears in record/view. I am trynig to find a way for the Administrator to enter the code returned by google oauth into the portal so that I can use it to generate credentials.
My current attempt looks something like this
row "Code from Google OAuth" do
form do |f|
label "Google Auth Code:"
input :code, :label => "Code", :hint => "Code returned by google auth"
f.action :submit
end
I get an "undefined method: action" error form this code. Any ideas on how to return user input as a parameter?
form is an Arbre tag that maps directly to HTML, in which case action is an attribute, eg.
form(action: '/someroute', method: :patch) do ... end
If you want to embed a Rails or Formtastic form you would use form_for or active_admin_form_for respectively.

Unable to login with Google plus using omniauth-google-oauth2

I am using gem "omniauth-google-oauth2" in my application built on spree(ruby-on-rails) to integrate Google plus login on to our site.I am getting a very strange error here,It's working fine in development(localhost),
but in production I am getting this error
"auth/google_oauth2/callback?state=35ad3c2e3f8327a5b96df7ce7e2439a77b90dfebc41f8463&code=4/p5l-nug7FU3P8lfnSHNF8Uy_tYXcLyqc0bnABoGo0EI#".
For integrating Google plus ,I have done following
a.) I created a WebApplication App in google developers console by adding necessary javascript origin and redirect url's
b.) I have added client id, secret in my coonfig file
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, 'my cient id', 'secret'
end
c.) I have added a route 'auth/google_oauth2/callback'
I am really struck here for quiet some time.
I have done google-omniauth-oauth2 for quite a few apps.
Based on my experience I am giving you some hints.
Some of the possible reasons could be
You have added ur production url to google console, but may have missed out on callback url for production.
Check for routes and see if you have added a callback route. Normally it should point to method 'sessions#create' in your SessionsController.
Try the following in omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET
{
:access_type => 'offline',
:prompt => 'consent'
}
Here is my sessions#create method for your reference
def create
auth = request.env['omniauth.auth']
#user = User.find_by_email(auth.info.email) || User.create_with_omniauth(auth)
if !#user.country
#user.country = request.location.country
end
#user.update_tokens auth
reset_session
session[:user_id] = #user.id
redirect_to new_video_path, :notice => 'Signed In!'
end
For more help check this link.

Testing expectations on doubles in Sinatra app using spec

I want to verify that a method was called on a service I want to inject into a Sinatra application using rspec but I can't find an example of how this is done. Here is my spec...
RSpec.configure do |config|
config.include Rack::Test::Methods
end
def app
App
end
describe 'Login' do
context 'when the user is logged out' do
describe 'POST on /signup' do
it 'invokes signup on the user service with the correct parameters' do
service = double('user_service').as_null_object
service.should_receive(:signup).with(:username => 'RobA2345')
post '/signup'
end
end
end
end
Here the App is a modular Sinatra app. I come from a .NET background and I'd use constructor injection here to solve this problem but I know this isn't the ruby way to do it.
Help, as always, is appreciated.
Assuming that you're expecting to receive the message on a new instance of UserService, there are a couple of ways to do this. If you are using a recent version of rspec, this should work:
it 'invokes signup on the user service with the correct parameters' do
UserService.any_instance.should_receive(:signup).with(:username => 'RobA2345')
post '/signup'
end
Alternatively, this should work in just about any version of rspec:
it 'invokes signup on the user service with the correct parameters' do
service = double('user_service').as_null_object
UserService.stub(:new).and_return(service)
service.should_receive(:signup).with(:username => 'RobA2345')
post '/signup'
end

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.

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