Don't use Date.today or Date.yesterday if you set config.time_zone / you do things similar to this post or this time zones railscast.
These two functions of Date don't mix well with Rails' time zone setting features.
Instead, use Time.now.in_time_zone to get the time in the right time zone you specified or Time.now.in_time_zone.to_date for the date.
Time.now just gets the time of the place where the server is running.
Basically, get a time object and convert as appropriate.
Showing posts with label ruby/rails. Show all posts
Showing posts with label ruby/rails. Show all posts
Monday, June 18, 2012
Tuesday, June 5, 2012
Images in public/ for error pages on Rails 3.1-3.2
For error pages found in public/ for a Rails 3.1 or 3.2 app, you might want to put a quick, simple image and reference it with the normal html img tag instead of any of Rails' fancy image_tag such and such.
Easy way that works:
1. Put images in public/images
2. Reference images like
Easy way that works:
1. Put images in public/images
2. Reference images like
<img src="/images/my-pic.jpg" />
Friday, November 4, 2011
Specifying miscellaneous attributes in a Rails text field
Quick code tip:
Specifying miscellaneous attributes in a Rails text field is easy.
Here's an example in which you set autocomplete="off":
The idea is to use "nil" as a placeholder for the middle value. In this case, the middle value for text_field_tag is value, which is what normally fills the text field.
If you didn't specify nil as a placeholder for the function, you would get a text field that said {:autocomplete=>"off"} inside. Probably something to avoid :)
Here's an example in which you set autocomplete="off":
<%= text_field_tag 'textfield', nil, :autocomplete=>"off" %>
The idea is to use "nil" as a placeholder for the middle value. In this case, the middle value for text_field_tag is value, which is what normally fills the text field.
If you didn't specify nil as a placeholder for the function, you would get a text field that said {:autocomplete=>"off"} inside. Probably something to avoid :)
Saturday, September 24, 2011
Setting optional local variables in your partials
Rails' partials are great - but sometimes, it's a hassle maintaining them.
For instance, haven't you ever changed the name of a partial, and consequently had to go find all your renderings of that partial and tediously adjust the name?
Or, have you ever decided to add a local variable requirement to a partial, and then have to, again, find all your renderings of that partial and then adjust the :locals => { :some_variable_I_now_have_to_set => "some value that shouldn't exist for most partials" } appropriately?
I don't have a solution to the first one (though I certainly wish I did), but I do - hooray! - for the second.
Basically, if you're thinking of doing something like this in your partial file...
So what do you do instead?
Voila. What does this mean you can do? Here's a more complete example:
books/index.html.erb:
partials/_book.html.erb:
stores/index.html.erb:
The stores/index file's partial call doesn't require the local variable that was passed into the partial call in books/index. Useful.
Basically, if you want to make the specification of a local variable in the render :partial call optional, use local_assigns[:variable_name].nil? This also checks to see that variable_name is nil if you specify :locals=>{ :variable_name=>nil }.
For instance, haven't you ever changed the name of a partial, and consequently had to go find all your renderings of that partial and tediously adjust the name?
Or, have you ever decided to add a local variable requirement to a partial, and then have to, again, find all your renderings of that partial and then adjust the :locals => { :some_variable_I_now_have_to_set => "some value that shouldn't exist for most partials" } appropriately?
I don't have a solution to the first one (though I certainly wish I did), but I do - hooray! - for the second.
Basically, if you're thinking of doing something like this in your partial file...
<% unless optional_local_variable.nil? %> <% end %>...you'll encounter an error saying that "optional_local_variable" is not defined, which is quite disturbing, considering that you wanted to check if it was nil to begin with.
So what do you do instead?
<% unless local_assigns[:optional_local_variable].nil? %> <% end %>
Voila. What does this mean you can do? Here's a more complete example:
books/index.html.erb:
Books
<%= render :partial=>"partials/book", :locals=>{ :books=>@books } %>
partials/_book.html.erb:
<% unless local_assigns[:books].nil? %>The 'books' variable was passed.<% else %>The 'books' variable was not passed.<% end %>
stores/index.html.erb:
Stores - Featured <%= render :partial=>"partials/book" %>
The stores/index file's partial call doesn't require the local variable that was passed into the partial call in books/index. Useful.
Basically, if you want to make the specification of a local variable in the render :partial call optional, use local_assigns[:variable_name].nil? This also checks to see that variable_name is nil if you specify :locals=>{ :variable_name=>nil }.
Saturday, August 6, 2011
PGError: ERROR: cached plan must not change result type... Solved
I got this error recently after deploying to Heroku:
It turns out the issue was just like that of this person: http://stackoverflow.com/questions/2783813/postgres-8-3-error-cached-plan-must-not-change-result-type.
Basically, I ran a migration / modified my database table, but didn't restart the heroku app. So, after running
I had to also run
and the problem was solved.
Why do we have to do this? According to this site on Heroku, "After running a migration you’ll want to restart your app with heroku restart to reload the schema and pickup any schema changes."
ActiveRecord::StatementInvalid (PGError: ERROR: cached plan must not change result type
It turns out the issue was just like that of this person: http://stackoverflow.com/questions/2783813/postgres-8-3-error-cached-plan-must-not-change-result-type.
Basically, I ran a migration / modified my database table, but didn't restart the heroku app. So, after running
heroku run rake db:migrate
I had to also run
heroku restart
and the problem was solved.
Why do we have to do this? According to this site on Heroku, "After running a migration you’ll want to restart your app with heroku restart to reload the schema and pickup any schema changes."
Thursday, August 4, 2011
Rails' link_to: specifying miscellaneous attributes
If you ever need to specify miscellaneous attributes, as I did when making my Rails 3.1 app mobile with jQuery Mobile, there's an easy way to do it.
Example: I want to create a link with the following...
Just do this (in your embedded ruby html file):
The order of the variables after the path specification (my_path, in this case) generally does not matter, so you could put :class => "my_class" before, in the middle, or after those "data-" parameters too, and you could rearrange the "data-" parameters however you like.
Also, note the specification of "data-prefetch"=>"" in the case that there is no attribute to set equal to.
This whole idea came especially in handy for me because jQuery mobile uses such things frequently. However, the idea of specifying
Example: I want to create a link with the following...
<a href="" data-direction="reverse" data-rel="back" data-prefetch>xyz</a>
Just do this (in your embedded ruby html file):
<%= link_to "xyz", my_path, "data-direction"=>"reverse", "data-rel"=>"back", "data-prefetch"=>"" %>
The order of the variables after the path specification (my_path, in this case) generally does not matter, so you could put :class => "my_class" before, in the middle, or after those "data-" parameters too, and you could rearrange the "data-" parameters however you like.
Also, note the specification of "data-prefetch"=>"" in the case that there is no attribute to set equal to.
This whole idea came especially in handy for me because jQuery mobile uses such things frequently. However, the idea of specifying
"some_variable"=>"some_value"in the link_to method can be applied to broader scenarios, too; it just might help you out.
Wednesday, August 3, 2011
Passing a path into a partial
I recently figured this out, and I thought others might find this helpful, too.
Ever want to pass a path into a partial - say, for a header, where there's always going to be a link in this one spot, but the actual path of that link changes? I encountered this problem when developing a mobile web app, where in the top left header section, I always wanted a "back" link, but the actual path of this link varied depending on the page.
Here's how I did it:
In the partial:
Instead of root_path, you could put, for example, books_path. Note, however, that passing "@book" or @book does not work, so this still has its limitations.
The whole trick is using the "send" method in the link_to. http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy/send
I certainly found this trick to be useful, and perhaps you will too.
Ever want to pass a path into a partial - say, for a header, where there's always going to be a link in this one spot, but the actual path of that link changes? I encountered this problem when developing a mobile web app, where in the top left header section, I always wanted a "back" link, but the actual path of this link varied depending on the page.
Here's how I did it:
In the partial:
<% unless path.nil? %> <%= link_to "Dining Hall", send(path) %> <% end %>In the view that renders the partial:
<%= render :partial => "layouts/partials/header", :locals => { :path => "root_path" } %>
Instead of root_path, you could put, for example, books_path. Note, however, that passing "@book" or @book does not work, so this still has its limitations.
The whole trick is using the "send" method in the link_to. http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy/send
I certainly found this trick to be useful, and perhaps you will too.
Saturday, July 30, 2011
Reducing Slug Size (Heroku)
If you check out http://devcenter.heroku.com/articles/slug-size, three tips are offered to reduce slug size:
I originally had the following in my Gemfile:
When I changed this to
I moved on to #2. I created a .slugignore file with the following contents:
In my case, just ignoring these folders in my app reduced my slug size from 61.6 MB to .... 61.6 MB. Negligible difference, unfortunately. I'm suspicious that adding the .slugignore didn't make a difference because when I set up this same app again at a different URL on heroku, the slug size was only 20.5 MB.
After filing a request to Heroku (https://support.heroku.com/requests/27593), I learned that, as the support staff member said, "There is currently a bug in bundler that is not cleaning old versions or unused gems out properly. We are working on upstreaming a fix for this, so hopefully sometime soon your slug size will lessen automatically with a push."
Guess it's back to waiting then. Nonetheless, I hope you found my little investigation above interesting if not helpful.
- Move large assets like PDFs or audio files to asset storage
- Ignore files which are unnecessary to run the app. For example, unit tests, PSDs, or large design documents.
- When possible, reference a released gem by name in your Gemfile rather than loading it from source using the :git option.
I originally had the following in my Gemfile:
gem 'rails', :git => 'git://github.com/rails/rails.git', :branch => '3-1-stable' gem 'sprockets', :git => 'git://github.com/sstephenson/sprockets.git'
When I changed this to
gem 'rails', '3.1.0.rc4' # :git => 'git://github.com/rails/rails.git' ... gem 'sprockets', '2.0.0.beta.10' # :git => 'git://github.com/sstephenson/sprockets.git'my slug size changed from 63 MB to 61 MB (specifically to 61.6 MB). But as Heroku recommends,
The maximum slug size is 100MB. Most apps should be far below this size. Anything under 10MB is good. If you exceed 40MB, you should think about trying to reduce the size of the slug....so I better keep going.
I moved on to #2. I created a .slugignore file with the following contents:
features test spec
In my case, just ignoring these folders in my app reduced my slug size from 61.6 MB to .... 61.6 MB. Negligible difference, unfortunately. I'm suspicious that adding the .slugignore didn't make a difference because when I set up this same app again at a different URL on heroku, the slug size was only 20.5 MB.
After filing a request to Heroku (https://support.heroku.com/requests/27593), I learned that, as the support staff member said, "There is currently a bug in bundler that is not cleaning old versions or unused gems out properly. We are working on upstreaming a fix for this, so hopefully sometime soon your slug size will lessen automatically with a push."
Guess it's back to waiting then. Nonetheless, I hope you found my little investigation above interesting if not helpful.
Thursday, July 21, 2011
Using PostgreSQL as your database for Ruby on Rails
The following blogpost does an outstanding job of explaining how to set up PostgreSQL for Ruby on Rails development on OS X (for Rails 3).
https://willj.net/2011/05/31/setting-up-postgresql-for-ruby-on-rails-development-on-os-x/
However, there is one part I want to draw attention to:
He says that it's okay to specify "No" for each of these, but you'll face a testing problem later:
Instead of replying "n" to "Shall the new role be allowed to create databases?" you should have replied "y" (yes) because using Rails' testing frameworks inherently requires that the test db is destroyed and regenerated frequently, as is shown by the existence of the rake command "rake db:test:prepare".
So what can you do now to fix the role? Instead of retracing your steps and making a new user with proper permissions, just change it via postgres:
1) Connect to the standard "postgres" db of your postgres installation (replace "your_username" with your username):
If you're not sure what your_username is, run the following; it's the name under "Owner" across from "postgres":
Note that not specifying your username might let you connect, too:
2) Run the postgres command:
That should do it. If interested, read on about useful postgres commands.
https://willj.net/2011/05/31/setting-up-postgresql-for-ruby-on-rails-development-on-os-x/
However, there is one part I want to draw attention to:
$ createuser shawsome Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) n Shall the new role be allowed to create more new roles? (y/n) n
He says that it's okay to specify "No" for each of these, but you'll face a testing problem later:
$ bundle exec rake db:test:prepare PGError: ERROR: permission denied to create database
Instead of replying "n" to "Shall the new role be allowed to create databases?" you should have replied "y" (yes) because using Rails' testing frameworks inherently requires that the test db is destroyed and regenerated frequently, as is shown by the existence of the rake command "rake db:test:prepare".
So what can you do now to fix the role? Instead of retracing your steps and making a new user with proper permissions, just change it via postgres:
1) Connect to the standard "postgres" db of your postgres installation (replace "your_username" with your username):
psql -U your_username postgres
If you're not sure what your_username is, run the following; it's the name under "Owner" across from "postgres":
psql -l
Note that not specifying your username might let you connect, too:
psql postgres
2) Run the postgres command:
ALTER ROLE that_username CREATEDB...where that_username is the username of your Rails application.
That should do it. If interested, read on about useful postgres commands.
Friday, July 15, 2011
link_to with image_tag
How do you use Rails' link_to helper with the image_tag helper in your views?
Easy:
Just surround the image_tag part with parentheses and place it where you'd typically put the text to display in your link_to.
Easy:
<%= link_to (image_tag "my_logo.png", :size => "150x50"), '/' %>
Just surround the image_tag part with parentheses and place it where you'd typically put the text to display in your link_to.
Monday, July 11, 2011
Sass partials with Rails 3.1 - use .css.scss
I tried importing partials in Sass for a Rails 3.1.rc4 app today, but for some reason, variables just wouldn't be recognized although they definitely existed in the partial.
The key thing is that your partials have to have the .css.scss extension - not the .scss extension as is shown on the Sass website (http://sass-lang.com/tutorial.html) explaining partial usage.
Here's an example of Sass used in my app:
assets/stylesheets/admin/meals.css.scss:
assets/stylesheets/partials/_standard_list.css.scss:
The key thing is that your partials have to have the .css.scss extension - not the .scss extension as is shown on the Sass website (http://sass-lang.com/tutorial.html) explaining partial usage.
Here's an example of Sass used in my app:
assets/stylesheets/admin/meals.css.scss:
// Place all the styles related to the admin/meals controller here. // They will automatically be included in application.css. // You can use Sass (SCSS) here: http://sass-lang.com/ @import "../partials/standard_list"; body { #meals_index { #meal_new_area { } ul#meal_list { @include standard_list(meal); } } }
assets/stylesheets/partials/_standard_list.css.scss:
@mixin standard_list($resource) { $light_green: #52D017; list-style-type: none; li { ul li { display: inline-block; } ul li.name { position: absolute; } ul li.controls { position: relative; margin-left: 300px; width: 200px; } ul##{$resource}_list_headers { li { font-weight: bold; } } ul.items_within_#{$resource} { li.name {} li.controls {} } ul:hover { background: $light_green; } } }
Sunday, July 3, 2011
Running multiple tags for Cucumber
If you want to run multiple tags at once, run something like this:
See this site for more info.
cucumber -t @a,@bNote that there should be no space after the comma. The sole separator is the comma.
See this site for more info.
Saturday, July 2, 2011
"Missing template" error with RSpec... Solved
If you ever get an error like...
Failure/Error: post :destroy, :id => organization.id
ActionView::MissingTemplate:
Missing template superadmin/organizations/destroy, application/destroy with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in:
* "#"
...when you run a spec test for a controller, and your routes are definitely fine and there shouldn't be a template for the action, you just need to specify a redirect_to or render.The person here - http://stackoverflow.com/questions/4628103/rspec-no-route-matches-error - had this problem too.
Thursday, June 30, 2011
undefined method `hash_for_... Solved.
Ever get a nasty error like this?
And I am on the controls page # features/step_definitions/web_steps.rb:44
undefined method `hash_for_new_admin_organization_path' for # (ActionView::Template::Error)
/Users/daze/.rvm/gems/ruby-1.9.2-p180@rails31/gems/actionpack-3.1.0.rc4/lib/action_dispatch/routing/polymorphic_routes.rb:133:in `polymorphic_url'
/Users/daze/.rvm/gems/ruby-1.9.2-p180@rails31/gems/actionpack-3.1.0.rc4/lib/action_dispatch/routing/polymorphic_routes.rb:140:in `polymorphic_path'
/Users/daze/.rvm/gems/ruby-1.9.2-p180@rails31/gems/actionpack-3.1.0.rc4/lib/action_view/helpers/url_helper.rb:111:in `url_for'
/Users/daze/.rvm/gems/ruby-1.9.2-p180@rails31/gems/actionpack-3.1.0.rc4/lib/action_view/helpers/url_helper.rb:242:in `link_to'
./app/views/admin/organizations/index.html.erb:4:in `_app_views_admin_organizations_index_html_erb___2726815532635892939_2153996520'
No worries. You probably just forgot something in your routes.rb file.
In my case, I had
<%= link_to "New Organization", new_admin_organization_path %>
in my view. Sure enough, I hadn't specified the new admin organization path in my routes file.
Solution: put the following in my routes file:
namespace :admin do resources :organizations endIf you find this helpful, feel free to comment below :].
Wednesday, June 29, 2011
Vacillating - just choose one
vacillate - verb (used without object): to waver in mind or opinion; be indecisive or irresolute
A few personal traits I want to improve on:
-patience
-making up my mind quickly
About the second one - it's important to have the mentality of just choose one! for the sake of productivity. Really... think about the cost of vacillating, of being uncertain. It eats up time better spent with something else, and it's especially bad if the issue is insignificant.
Here's one example (beware: 99% of you won't know what I'm talking about): choose Webrat or Capybara. They're both testing frameworks for Ruby on Rails, and I ended up choosing Capybara because (1) it has ongoing support and (2) whoever I asked seemed to be using it. There, done and done. Even if I had gone the other way, it's no big deal.
A few personal traits I want to improve on:
-patience
-making up my mind quickly
About the second one - it's important to have the mentality of just choose one! for the sake of productivity. Really... think about the cost of vacillating, of being uncertain. It eats up time better spent with something else, and it's especially bad if the issue is insignificant.
Here's one example (beware: 99% of you won't know what I'm talking about): choose Webrat or Capybara. They're both testing frameworks for Ruby on Rails, and I ended up choosing Capybara because (1) it has ongoing support and (2) whoever I asked seemed to be using it. There, done and done. Even if I had gone the other way, it's no big deal.
Okay, if that example flew over your head, then think about day-to-day things. Here's one: Which homework do I do first? If you're a high school student staring blankly at assignments crudely jotted down in your planner, wondering where to start, just choose one! In the end, you're going to do them all anyway (right?), so it's inconsequential where you start. The impact is just... nil.
So you probably get the idea that I appreciate maximum efficiency. Very true.
I really strive to make my time as productive as possible - which, actually, might tie to my patience threshold...
Tuesday, June 28, 2011
Authlogic steaming issue in Rails 3.1
At the moment, there's a streaming issue with Authlogic and Rails 3.1:
https://github.com/binarylogic/authlogic/issues/262#issuecomment-1460466
Apparently, Authlogic violates MVC in some entrenched way, and consequently this gem breaks Rails 3.1's new streaming. Hopefully there will be a solution soon, but for now, if you get a
(as I did when I run my cucumber tests together), you'll have to make do and e.g. run your cucumber tests independently by using tags (example: cucumber -t @authlogic-one).
Apparently, Authlogic violates MVC in some entrenched way, and consequently this gem breaks Rails 3.1's new streaming. Hopefully there will be a solution soon, but for now, if you get a
"Cannot modify cookies because it was closed. This means it was already streamed back to the client or converted to HTTP headers. (ActionDispatch::ClosedError)"
(as I did when I run my cucumber tests together), you'll have to make do and e.g. run your cucumber tests independently by using tags (example: cucumber -t @authlogic-one).
(.+) and ([^"]*) - Regexps
The Cucumber testing framework of Rails generates "([^"]*)" if you have an undefined step like
Misc. Tags: regexp, regular expression
Given a user named "John"But you can also use "(.+)" or if you don't want the quotes, simply (.+). Basically, (.+) and ([^"]*) are equivalent.
Misc. Tags: regexp, regular expression
Monday, June 27, 2011
Using MySQL as your development database
On my Mac OS X, I'm starting a new project with Rails 3.1, and I'm using MySQL as my development database because when I deploy, MySQL will be the production database, and the two dbs really should match.
# start the server - something I'm not used to after using sqlite
Unfortunately, after running
rails new mynewapp -d=mysqland testing out
rails serverI got this error:
error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)'
Of course I hadn't (1) started the MySQL server yet and (2) created my development database. This was new to me since I normally just developed with the sqlite db Rails automatically ships with for development.
After using homebrew to install mysql ("brew install mysql" as Ryan Bigg suggests at http://ryanbigg.com/2011/06/mac-os-x-ruby-rvm-rails-and-you/), I followed the added installation instructions that come with the brew install (viewable through "brew info mysql"
- pretty darn important to finish the mysql install with homebrew), and then ran these commands:
- pretty darn important to finish the mysql install with homebrew), and then ran these commands:
# start the server - something I'm not used to after using sqlite
mysql.server start# create the db; specify -p if necessary
mysqladmin -u root create mynewapp_development
Then, "rails server" was successful.
(Note: running "mysql.server start" won't be necessary if you follow the instructions from "brew info mysql" and configure the start server on startup)
Friday, June 17, 2011
Speed test: rake vs. rspec spec, rake cucumber vs cucumber
I timed different rspec commands to see which ran faster.
These tests were done on a really old machine so the times would be drawn out.
Newer machines execute far quicker with negligible difference.
(Precondition: all tests run with regard to the same code.)
Test 1: rake spec:controllers vs. rspec spec/controllers
Results:
rake spec:controllers --> 23 seconds
Test 2: rake spec:models vs. rspec spec/models
Results:
rake spec:models --> 34 seconds
rspec spec/models --> 16 seconds
Test 3: rake spec:views vs. rspec spec/views
Test 4: rake spec vs. rspec spec
Results:
Conclusion: It is faster to use "rspec spec/..." than the broader "rake spec" command.
This makes sense because the rake command has to invoke the Rakefile first, and from what I've seen online, "rake spec" and "rake cucumber" also invoke "rake db:test:prepare" behind the scenes first - a necessary command to restore the test database from scratch if you blew away the old one.
Here's one more test I did - this time, with cucumber:
Test 5: cucumber vs. rake cucumber
Results:
Yep.
Test 1: rake spec:controllers vs. rspec spec/controllers
Results:
rake spec:controllers --> 23 seconds
rspec spec/controllers --> 15 seconds
Test 2: rake spec:models vs. rspec spec/models
Results:
rake spec:models --> 34 seconds
rspec spec/models --> 16 seconds
Test 3: rake spec:views vs. rspec spec/views
Results:
rake spec:views --> 20 seconds
rspec spec/views --> 11 seconds
Results:
rake spec --> 20 seconds
rspec spec --> 11 seconds
This makes sense because the rake command has to invoke the Rakefile first, and from what I've seen online, "rake spec" and "rake cucumber" also invoke "rake db:test:prepare" behind the scenes first - a necessary command to restore the test database from scratch if you blew away the old one.
Here's one more test I did - this time, with cucumber:
Test 5: cucumber vs. rake cucumber
Results:
rake cucumber --> 30 seconds
cucumber --> 21 seconds
Yep.
Tuesday, June 14, 2011
Capybara (click_link, JS problem) & Logging in directly with Authlogic
The click_link / JS problem
I'm using capybara, and I recently came across this error:
This is the kind of error that arises if the link you want to click has href="javascript:void(0)". In my case, my link was
With the help of jQuery, this link toggles a div for the login form, but there is no easy way to test this with Capybara because Capybara uses RackTest, which doesn't execute JS.
My solution: avoid the complications of this JS testing (I'm positive it works anyway), and instead forcibly create user session to login. After all, that's the whole point of this logging in thing - it should be preliminary for what I really want to test.
Logging in directly with Authlogic
I am using Authlogic (https://github.com/binarylogic/authlogic) for user validation.
While trying code like UserSession.create!(:login => etc., :password => "some_password" ...), I came across this error:
Yep.
Unfortunately, in the end even there still were problems with the "save" method no longer working - something about the improper number of arguments.
So, my FINAL solution was that I had to use the Cucumber steps of navigating to some page, filling in the login form, clicking the button, etc. I guess there never really was a good solution to all of this, so I recommend against using the type of link I did above (a link that opens a little form on the page).
I'm using capybara, and I recently came across this error:
Given I am on the home page # features/step_definitions/web_steps.rb:42
And I am the registered poster "John Doe" # features/step_definitions/user_steps.rb:1
When I log in # features/step_definitions/user_steps.rb:11
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[] (NoMethodError)
(eval):2:in `click_link'
./features/step_definitions/user_steps.rb:12:in `/^I log in$/'
features/users_have_basic_abilities.feature:10:in `When I log in'
This was my step definition:When /^I log in$/ do click_link "Login" end
This is the kind of error that arises if the link you want to click has href="javascript:void(0)". In my case, my link was
<a href="javascript:void(0)" id="login_activator">Login</a>
With the help of jQuery, this link toggles a div for the login form, but there is no easy way to test this with Capybara because Capybara uses RackTest, which doesn't execute JS.
My solution: avoid the complications of this JS testing (I'm positive it works anyway), and instead forcibly create user session to login. After all, that's the whole point of this logging in thing - it should be preliminary for what I really want to test.
Logging in directly with Authlogic
I am using Authlogic (https://github.com/binarylogic/authlogic) for user validation.
While trying code like UserSession.create!(:login => etc., :password => "some_password" ...), I came across this error:
You must activate the Authlogic::Session::Base.controller with a controller object before creating objects (Authlogic::Session::Activation::NotActivatedError)The solution: ensure the following code is executed before such a user session creation:
Authlogic::Session::Base.controller = Authlogic::ControllerAdapters::RailsAdapter.new(self)
Yep.
Unfortunately, in the end even there still were problems with the "save" method no longer working - something about the improper number of arguments.
So, my FINAL solution was that I had to use the Cucumber steps of navigating to some page, filling in the login form, clicking the button, etc. I guess there never really was a good solution to all of this, so I recommend against using the type of link I did above (a link that opens a little form on the page).
Subscribe to:
Posts (Atom)