Rack::Test not able to find web app cookie - ruby

While testing a Sinatra app with Cucumber, Rack::Test was not able to find the cookie that my app created, even though I could clearly see that it was in the Rack::Test::CookieJar object by dumping it with "p".

I'm answering my own question in order to share the solution with others:
Rack::Test::CookieJar#[] will only return the value of a cookie if it also matches the domain and path. Unfortunately, unless your app's domain is "example.org" you're out of luck.
Fortunately, there's an easy fix: If you're testing with Sinatra, paste the following monkey patch anywhere in your env.rb file in the outermost (global) scope:
module Rack
module Test
DEFAULT_HOST='localhost'
end
end
That's it!

Related

Changing the base URL for Capybara Acceptance Tests

I am developing a sinatra based web application and I extensively use tests to make sure that everything is working before deployment. As testing frameworks I use minitest::specs and capybara with webkit.
My problem is that after deployment my application runs with a base url like this:
http://cool.server.net/to-the-application/
But during tests capybara assumes a clean base-url with a path to / not to to-the-application/. This means I can't test to find bugs which relate to forgetting to set the base-url within links and actions.
For dry testing I followed Changing the base URL for Rails 3 development and modified my config.ru, but I haven't found any way to get capybara to use a different base.
Any ideas how to solve this?
If using the rack_test driver the hostname is completely ignored so changing it isn't going to do anything. If using a different driver you can specify
Capybara.app_host = "http://cool.server.net"
Note that cool.server.net would generally need to resolve to 127.0.0.1 since thats where Capybara binds the app being tested.
Update: After thinking about this I'm not sure that is what you wanted. If what you want is for Capybara to mount your app under /to-the-application then you're going to have to create your own app object which you assign to Capybara.app - see https://github.com/teamcapybara/capybara/blob/2.13_stable/lib/capybara/rails.rb#L4 for how Capybara currently mounts the app.

Annoying Guard notification when testing

Recently I made a simple ruby application and have been using minitest to test it.
Following the advice of the Head First Ruby book, I automated this testing using Rake(I'll write what it told me to put in the Rakefile at the end of this post, in case that helps). The test seems to run fine (everything passes in a way I would expect it to), but I always get this notification at the end of it all:
rvm/gems/ruby-2.3.0/gems/guard-2.14.0/lib/guard/notifier.rb:28: warning: instance variable #notifier not initialized
Testing things manually by telling ruby to include which files I want, does not have this issue, only when I use "rake test" to test things.
As far as I can tell, this is related to when I set up Guard when I was following Michael Hartl's Rails Tutorial, at the end of chapter 3. I followed the directions for setting that up (correctly, as far as I can tell), and this was all in a completely different folder(ultimately my ruby and rails projects do have the same parent folder that they sit in, but are themselves in completely separate ruby_projects and rails_projects folders). If possible, I would like to stop this notification on my ruby application that I am testing. Is there a good way to do this?
Contents of the Rakefile I am using, if that helps:
require "rake/testtask"
Rake::TestTask.new(:test) do |t|
t.libs << "lib"
t.test_files=FileList['test/**/test_*.rb']
end
My test file requires minitest/autorun, and the file for the application that I am testing, then has the normal tests
Seems like there's some weird conflict...
The reason is that Guard::Notifier.connect isn't connected. Normally, when you run guard, Guard.setup is called which does this.
If you're not using guard (e.g. interactively), then calling the following from your Rakefile should work around the problem:
Guard::Notifier.connect(notify: false, silent: true)
Guard::Notifier.disconnect
This will initialize the variable.
For a faster response, always report such issues on the project page on Github. If you can share the project where this occurs, maybe a better fix is possible. (It's best to provide a repository, since it really speeds up fixing things and often errors like this are very hard to simulate without the exact code).

Espresso Enginery

i use framwork Espresso with Enginery generator (Ruby gems). I create new project, and not understand how work this application. I will work with Espresso. Explain me struct Expresso Application, please.
I can run this apllication: rackup config.ru
I can edit controllers, but i not understand depending between ruby scripts in this project.
i run projects, but why this work it?
config.ru
require File.expand_path('../base/boot', __FILE__)
puts App.urlmap
run App
in project not /base/boot directory.
requiring '../base/boot' will actually load dependencies, controllers, models etc. and build the application.
The application are stored under App constant, so you can access it from different files:
https://github.com/espresso/enginery/blob/master/app/base/base/boot.rb#L9
puts App.urlmap will display all the routes to be served by app.
And run App will start your app.
You can also start app by ruby app.rb, then you do not need to pass server/port at startup.
Instead you'll set them in config/config.yml, like this:
development:
server: Thin
port: 5252
The config.ru file looks quite normal for a rack start-up file. You would start the application from the project folder, with a command like:
rackup -p 8080
The following line:
require File.expand_path('../base/boot', __FILE__)
will load in the ../base/boot file (similar to require_relative, but also works with older Ruby e.g. 1.8.7), which I would guess requires the dependencies where App is defined. The class or module App will implement a call method. To start the server, the rack host calls App.new (which is called due to run App) and then on each request it will call .call( env ) on the resulting object (the object doesn't have to be an App object, but in simpler frameworks it will be).
The variable env contains all the details of the request and the rack environment that can be inspected to fetch details of the current path, cookies, query params etc. Typically access to this data is abstracted through Sinatra and Espresso helper methods that you will use.
The Sinatra and Espresso helper methods look like they are doing magic declarations, but they are just normal methods. Usually they do some calculation and then stash a code block/lambda for rack to call later. Sinatra's get is like this . . . it isn't true declarative code. Instead, when the controller is parsed, it just takes the code block and tells the application object to call it (later) when the path matches.

Ruby: Get currently logged in user on windows

In C# I can get the current user of a web app using the HttpContext, however, I can't figure out how to do this in Ruby. Is there any way of doing this?
FOR THOSE OF YOU SAYING IT IS IMPOSSIBLE, HERES PROOF:
http://www.codeproject.com/KB/aspnet/How_to_NT_User_Name.aspx
Well, to get the current username, there's this:
puts ENV['USERNAME']
Or go to the Win32API.
require 'dl/win32'
def get_user_name
api = Win32API.new(
'advapi32.dll',
'GetUserName',
'PP',
'i'
)
buf = "\0" * 512
len = [512].pack('L')
api.call(buf,len)
buf[0..(len.unpack('L')[0])]
end
puts get_user_name
Edit: And I'm an idiot. This isn't what you asked for at all. Oh well, it took me time to dig this out of my code, so it might as well stay here for anyone else wondering :P
Edit again: OK, it turns out I'm not an idiot after all. This is what you want. When I went back and re-read your question, the HttpContext threw me off, and I thought it was the current username from HTTP auth or something.
To get the username of the current user on client machine you can use this
ENV['USERNAME']
If you're using Rails try: request.env['HTTP_REMOTE_USER']
I think what you mean is how you can retrieve the username that the user used to login to the web application. That will differ depending on what authentication mechanism you're using. Some Apache authentication modules, for example, will pass REMOTE_USER (e.g. the Kerberos module), the CAS Single-Sign-On module passes CAS-USER, etc. Standard digest authentication and such uses the Authentication header. You should be able to access these using request.env[HEADER] as someone else pointed out above. Check out the documentation on how your authentication layer is passing on the user in the HTTP request.
Is your c# code running as a .NET plugin/client-side code or is it ENTIRELY server side? Your ruby code would be entirely server side. According to the MS docs, only stuff running in the CLR sandbox can really get to that information:
http://msdn.microsoft.com/en-us/magazine/cc163700.aspx (under Defining the sandbox).
One thing interesting to note is that sites registered under LocalIntranet have access to that information. I'm not sure off hand how this maps to security zones in IE though.
The thing to understand is that LOGON_USER is NOT visible to the browser sandbox anymore than the browser can see the contents of a filesystem path on your system. The fact that your c# code sees it almost certainly indicitive of some clientside component passing it upstream.
You have the option of implementing mod_ntlm under apache and pushing the headers downstream. I don't have the points to post a second link but google 'rails ntlm sso' and see the rayapps.com link.
but if your app isn't Rails based, you'll have to port that to your server code. You can also checkout rack-ntlm if your app is rack compliant.
[RUBY ON RAILS ONLY]
This is what worked for me but there are some limitations:
won't work in Chrome: undefined method 'encode' for nil:NilClass
won't validate user credentials
If you don't care about these issues, go ahead:
In your rails application, add Rekado's gem to your Gemfile: gem 'ntlm-sso', '=0.0.1'
Create an initialiser config/initializers/ntlm-sso.rb with:
require 'rack'
require 'rack/auth/ntlm-sso'
class NTLMAuthentication
def initialize(app)
#app = app
end
def call(env)
auth = Rack::Auth::NTLMSSO.new(#app)
return auth.call(env)
end
end
On your application.rb file, add the line: config.middleware.use "NTLMAuthentication"
Call request.env["REMOTE_USER"] on your view or controller to get current username.
PS: Let me know if you find anyway to make it work on Chrome or to validate user credentials.

Stubbing Sinatra helper in Cucumber

I am currently struggling with stubbing out a helper method of my Sinatra app from within Cucumber.
I have a Sinatra app with simple session authentication (by cookies) and I want to turn of authentication by stubbing out the logged_in? helper method for my Cucumber scenarios.
There seems to be a problem with Sinatra and Cucumber concerning sessions so I thought about just using Mocha to work around the problem.
However I don't know how I can access the Sinatra::Application instance from within a Given-Block to stub out the method.
It seems like I need to directly override my Authentication mechanism within a Before do ... end-block
So I ended up with a hooks.rb placed in features/support/ file overwriting my logged_in? and the current_user method.
Before do
MySinatraApplicationClass.class_eval do
helpers do
def logged_in?
return true
end
def current_user
# This returns a certain Username usually stored
# in the session, returning it like
# that prohibits different user logins, but for
# now this is enough for me
"Walter"
end
end
end
end
The only thing I had to take care of, is that the no other actions within the application directly read from session but rather use those helpers.
Sadly I think this way of handling session based Sinatra applications through Cucumber is already described somewhere else and I just thought my problem was different.
You can get the right context by using Sinatra::Application.class_eval
Edit: See original poster's answer for full explanation.

Resources