Cucumber Capybara Undefined Method for objects - ruby-on-rails-3

I've been trying to do the RSpec Book, the cucumber simulated browser part. The problem is that it keeps throwing undefined method for any object, meaning it can't test the application.
The test
When /^I create a movie Caddyshack in the Comedy genre$/ do
visit movies_path
click_link "Add Movie"
click_button "Save"
end
The problem is that it won't render the form with the view, throwing undefined error for ActiveRecord objects.
The view
<%= form_for(#movie) do |f| %>
<table>
<tr>
<th><%= f.label :name %></th>
<td><%= f.text_field :name, :id => "title" %></td>
</tr>
</table>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
The controller
def index
#movies = Movie.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #movies }
end
end
def new
#movie = Movie.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #movie }
end
end
The Model
class Movie < ActiveRecord::Base
attr_accessible :showtime_date, :showtime_time, :name
has_many :genres
def showtime
"#{formatted_date} (#{formatted_time})"
end
def formatted_date
showtime_date.strftime("%B %d, %Y")
end
def formatted_time
format_string = showtime_time.min.zero? ? "%l%p" : "%l:%M%p"
showtime_time.strftime(format_string).strip.downcase
end
end
My Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'sqlite3'
gem 'awesome_print'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
group :development, :test do
gem "rspec-rails", ">= 2.0.0"
end
group :test do
gem 'database_cleaner'
gem "cucumber-rails", ">= 0.3.2"
end
Finally, the error that capybara keeps telling me
When I create a movie Caddyshack in the Comedy genre # features/step_definitions/genre_steps.rb:6
undefined method `name' for #<Movie:0x00000102e36590> (ActionView::Template::Error)
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.8/lib/active_model/attribute_methods.rb:407:in `method_missing'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/attribute_methods.rb:149:in `method_missing'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:1161:in `value_before_type_cast'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:1149:in `value_before_type_cast'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:1043:in `block in to_input_field_tag'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:1043:in `fetch'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:1043:in `to_input_field_tag'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:692:in `text_field'
/Users/Dono/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_view/helpers/form_helper.rb:1284:in `text_field'
./app/views/movies/_form.html.erb:5:in `block in _app_views_movies__form_html_erb___3270649907202408240_2157451180'
My features/support/env.rb
require 'cucumber/rails'
require 'rspec'
Capybara.default_selector = :css
ActionController::Base.allow_rescue = false
begin
DatabaseCleaner.strategy = :transaction
rescue NameError
raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end
Cucumber::Rails::Database.javascript_strategy = :truncation
Yet the name method is defined and the page renders fine in my browser. Any idea on what might be going wrong?

As stated by RobertH in the comments, I wasn't setting the test database. All I needed to do was to run
rake db:test:prepare

Related

Rails get random yoda giphy API image to show on 'welcome/yoda'

I got the translate yoda API to work from mashape. https://github.com/sfinley89/BEWD_midcourse
Now Im trying to get random yoda giphy images to show up on the 'welcome/yoda' page when their text is translated into yoda speak.
Here is what im getting right now showing on the 'welcome/yoda'
Yoda Says, "Lets gets some gifs alrady. "
#<Giphy::RandomGif:0x007ffae5467e08>
#<unirest::httpresponse:0x007ffae57a23e8>
{"data"=>{"type"=>"gif", "id"=>"PciMitIKp0UjS", "url"=>"http://giphy.com/gifs/yoda-PciMitIKp0UjS", "image_original_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.gif", "image_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.gif", "image_mp4_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.mp4", "image_frames"=>"21", "image_width"=>"150", "image_height"=>"190", "fixed_height_downsampled_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/200_d.gif", "fixed_height_downsampled_width"=>"158", "fixed_height_downsampled_height"=>"200", "fixed_width_downsampled_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/200w_d.gif", "fixed_width_downsampled_width"=>"200", "fixed_width_downsampled_height"=>"253", "fixed_height_small_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100.gif", "fixed_height_small_still_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100_s.gif", "fixed_height_small_width"=>"79", "fixed_height_small_height"=>"100", "fixed_width_small_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100w.gif", "fixed_width_small_still_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100w_s.gif", "fixed_width_small_width"=>"100", "fixed_width_small_height"=>"127", "username"=>"", "caption"=>""}, "meta"=>{"status"=>200, "msg"=>"OK"}}
Back
How do I get this to show the random yoda gif?
Here is my controller welcome_controller.rb
class WelcomeController < ApplicationController
def index
#ask
end
def ask
end
def yoda
##voice = HTTParty.get('https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.').parsed_response
#sentence = "You+will+learn+how+to+speak+like+me+someday.++Oh+wait."
sentence = params[:sentence]
#render plain: ENV["YODA_KEY"]
#response = Unirest.get "https://yoda.p.mashape.com/yoda?sentence="+sentence,
headers:{
"X-Mashape-Key" => ENV["YODA_KEY"],
"Accept" => "text/plain",
}
#gifpic = Unirest.get "http://api.giphy.com/v1/gifs/search?q=Yoda&api_key=dc6zaTOxFJmzC"
#gif = Giphy.random('Yoda')
url = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=yoda"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
#result = JSON.parse(buffer)
end
end
Here is my welcome/index.html.erb
<center>
<h2>Midcourse Project</h2><br>
<br>
<%= link_to "Ask Yoda How He Would Say It!", 'welcome/ask' %>
<br><br><br><br><br><br>
<%= image_tag "http://www.extension.zone/wp-content/uploads/2015/05/Giphy-logo.jpg", size: "200x100", :alt => 'logo' %>
</center>
Here is welcome/ask.html.erb
<center>
<h1> I am yoda! What do you want me to say? </h1><br>
<%= form_tag "/welcome/yoda" %>
<%= text_field_tag :sentence %>
<%= submit_tag "Submit" %>
</center>
Here is welcome/yoda.html.erb
<p> Yoda Says, "<%= p #response.raw_body %>"</p> <br>
<%= #gif %> <br>
<%= image_tag #gifpic %> <br>
<%= p #result %>
<br>
<%= link_to "Back", '/welcome/ask' %>
Here is my gemfile
source 'https://rubygems.org'
# unirest http://unirest.io/ruby
gem 'unirest', '~> 1.1', '>= 1.1.2'
# HTTParty
#gem 'httparty', '~> 0.13.7'
# Gem from https://rubygems.org/gems/giphy/versions/3.0.0
# gifs https://github.com/sebasoga/giphy
gem 'giphy', '~> 3.0'
# Geocoding https://github.com/alexreisner/geocoder
gem 'geocoder'
# Yelp https://github.com/Yelp/yelp-ruby
gem 'yelp', require: 'yelp'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
And here is the routes.rb
Rails.application.routes.draw do
# get the yoda page
get 'welcome/yoda'
# post to the yoda page
post 'welcome/yoda'
# get the ask page
get 'welcome/ask'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'welcome#index'
end
Documentation:
on github checkout /Giphy/GiphyAPI
or /sebasoga/giphy
Please help me out with this.
Answer: <%= image_tag #result["data"]["image_url"] %> put this in your views where you want it displayed.
Change controller welcome_controller.rb to look like
class WelcomeController < ApplicationController
def index
#ask
end
def ask
end
def yoda
##voice = HTTParty.get('https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.').parsed_response
#sentence = "You+will+learn+how+to+speak+like+me+someday.++Oh+wait."
sentence = params[:sentence]
#render plain: ENV["YODA_KEY"]
#response = Unirest.get "https://yoda.p.mashape.com/yoda?sentence="+sentence,
headers:{
"X-Mashape-Key" => ENV["YODA_KEY"],
"Accept" => "text/plain",
}
url = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=yoda"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
#result = JSON.parse(buffer)
end
end
Change view welcome/yoda.html.erb to look like
<p> Yoda Says, "<%= p #response.raw_body %>"</p> <br>
<%= image_tag #result["data"]["image_url"] %>
<br>
<%= link_to "Back", '/welcome/ask' %>

Devise : undefined method `user_signed_in? Didn't know why?

Please help i am using rails 3.2.11 and devise 2.0.6 but when i am trying to run my project i am getting an error undefined method `user_signed_in?' for Class
i have done lot of google but didnt find any solution.!
Below is my application trace
NoMethodError in Home#index
Showing /home/amits/RailsWorkspace/Myapp/app/views/home/index.html.haml where line #3 raised:
undefined method `user_signed_in?' for #<#<Class:0xbb1f3f4>:0xbae60b8>
Extracted source (around line #3):
1: %h2= (t :welcome) + " Myapp"
2:
3: - if user_signed_in?
4: = link_to (I18n.t :customers), user_root_path
5: / %li
6: / = link_to (I18n.t :sign_out), destroy_user_session_path, :method => :delete
Rails.root: /home/amits/RailsWorkspace/Myapp
Application Trace | Framework Trace | Full Trace
app/views/home/index.html.haml:3:in `_app_views_home_index_html_haml___806580830_97751900'
Request
Parameters:
None
Show session dump
Show env dump
Response
Headers:
None
and my gem file is as follows
Gemfile :
source 'https://rubygems.org'
gem 'rails', '3.2.11'
gem 'heroku'
gem 'pg'
gem 'haml'
gem 'haml-rails', :group => :development
gem 'rmagick'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.0'
gem 'uglifier', '>= 1.0.3'
end
gem "devise", "~> 2.0.0"
gem 'devise_aes_encryptable'
# version added so that the gem version will be stable at this point.
gem 'geokit', '1.5.0'
gem 'geokit-rails3', '0.1.5'
My Home controller
Homescontroller.rb
class HomeController < ApplicationController
before_filter :authenticate_user!
def index
end
end
My user model
User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :token_authenticatable, :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :sign_in_count
end
Rotes.rb
Myapp::Application.routes.draw do
devise_for :users
root to: "home#index"
end
Please help me....
Try removing 'clear_helpers' method in ApplicationController as it might block sometimes Devise to load his helpers.

Recaptcha with devise is not working on ruby on rails?

I get this error:
There has been an unexpected error with the application. Please contact the administrator. error code: success
I am using recaptcha with devise, I edited where appropriate as stated by following the steps mentioned on this page
Here is my Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'json'
gem 'execjs'
gem 'therubyracer'
gem 'will_paginate', "3.0.pre4"
group :production do
gem 'pg'
end
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
gem 'jquery-fileupload-rails'
gem "letter_opener"
gem 'jquery-ui-rails'
end
gem 'jquery-rails'
gem "carrierwave"
gem "fastercsv"
gem 'devise', '2.1.2'
gem 'rmagick'
gem 'mailman', :require=> false
gem 'activeadmin'
gem 'kaminari'
gem 'prawn'
gem 'recaptcha', :require => 'recaptcha/rails'
I hope you have followed it exactly what it says on the documentation For instance, to support recaptcha on ruby 1.8.X and 1.9.X, there are different line of code. However, after a short research I found out this website you can use recaptcha without the plugins regardless of your rails version. I hope this helps. :)
From Recaptcha Site (almost).... I'm in Rails 4 with Devise (aparently the hard bundle).. No, is too easy. Procedure apply to any ruby, any rails, and devise (or without devise). Tested in ruby/rails/devise 1.9.3/3.2.x/2.2.1 & 2.0.x/4.0.x/3.2.4 and last one without Devise.
Edit next files:
Gemfile
gem 'ruby-recaptcha'
# bundle install
config/initializers/credentials.rb (any file in this path it's ok)
# Set constants
RCC_PUB = "your_public_key"
RCC_PRIV= "your_private_key"
# re-start server. Try to keep safety this data using ENV vars.
app/views/devise/registrations/new.html.erb (or form you prefer)
# form
<%= simple_form_for(resource, as: resource_name, :url => registration_path(resource_name) do |f| %>
<%= f.input :email, autofocus: true, required: true %>
...
<!-- Add next line -->
<div id="captchadiv"></div>
<%= f.button :submit, "Register", class: 'btn btn-danger' %>
<% end %
At the end of same file (can be in awesome_funcs.js.erb file)
<script type="text/javascript" charset="utf-8">
$(function () {
function showRecaptcha() {
Recaptcha.create("<%= RCC_PUB %>", "captchadiv", {
theme: "white",
lang: 'en'
});
};
showRecaptcha();
});
</script>
And the little trick, app/controllers/application_controller.rb
# On top
include ReCaptcha::AppHelper
before_action :configure_permitted_parameters, if: :devise_controller?
# If already you have this method or any other with before_filter
# Into method
protected
def configure_permitted_parameters
if controller_name == "registrations" && action_name == "create"
# Rails 3: If you prefer, put this into registrations#create method
unless validate_recap(params, User.new.errors) # Or your model
# wrong input is handled here
flash[:error] = "Text from images doesn't match with your input"
redirect_to :back # or other stuff
# As my submit is with Ajax, I do a render instead redirect:
# render :json => {other: "recaptcha_failed"}
# In success callback I evaluate response and Recaptcha.reload() paints a new recaptcha.
end
end
....
# trick: do everything before params sanitizers
end
As we are using Ajax plugin, finally, add in
app/views/layouts/application.html.erb
(just before end of body)
<body>
...
...
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
</body>
That's it. You have recaptcha
Advice:
If you use Ajax to do submit, you can use success callback for a Recaptcha.reload() in case images and input doesn't match.
Other, if your form is "remote: true", you can use above behavior after "create" method in create.js.erb file in your views directory.
IMPORTANT: In some projects when form arrives from a link Recaptcha doesn't appear. Try to locate the launcher link into a div or in a parent div add "data-no-turbolink". I had this issue in Rails 4.

Rails 3.2.11 Asset Pipeline in development issue (don't load assets)

I was creating a new app using ZURB Foundation.
There are three controllers. And ih one of them - everything works fine, all css and javascripts includes everytime when i run the server in development. But if i run my Projects#Controller, it gets only plain html, without loading javascripts and css. I tried everything, but still dunno what to do with it.
Here is the logs from the console:
When it works fine
Started GET "/" for 127.0.0.1 at 2013-01-09 21:36:21 +0200
Processing by PagesController#info as HTML
Rendered pages/info.html.erb within layouts/application (0.3ms)
Rendered layouts/_head.html.erb (36.9ms)
User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Rendered layouts/_header.html.erb (8.9ms)
Rendered layouts/_flash_messages.html.erb (0.3ms)
Rendered layouts/_footer.html.erb (66.0ms)
Completed 200 OK in 368ms (Views: 365.2ms | ActiveRecord: 1.6ms)
But then if i go to another page from the other controller it loads only plain html from the page
Started GET "/projects/" for 127.0.0.1 at 2013-01-09 21:23:21 +0200
Processing by ProjectsController#index as HTML
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Project Load (0.5ms) SELECT "projects".* FROM "projects" WHERE "projects"."user_id" = 1 ORDER BY created_at desc
Rendered projects/index.html.erb (30.8ms)
Completed 200 OK in 78ms (Views: 38.4ms | ActiveRecord: 2.7ms)
Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.11'
group :development, :test do
gem 'sqlite3'
gem 'rspec-rails'
gem 'factory_girl_rails'
end
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'compass-rails'
gem 'zurb-foundation'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'devise'
gem 'thin'
gem 'best_in_place'
group :test do
gem 'capybara'
gem 'shoulda-matchers'
end
group :production do
gem 'pg'
end
application.html.erb
<!DOCTYPE html>
<html lang="en">
<head>
<%= render 'layouts/head' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container-fluid">
<div class="row-fluid">
<div class="span8 offset2">
<%= render 'layouts/flash_messages' %>
<%= yield %>
</div>
</div>
</div>
<div class='row-fluid'>
<%= render 'layouts/footer' %>
</div>
</body>
</html>
And Controllers
class PagesController < ApplicationController
respond_to :html
def info
end
end
class ProjectsController < ActionController::Base
# before_filter :authenticate_user!
def index
#projects = current_user.projects
respond_to do |format|
format.html
end
end
end
Any help or ideas will be greatly appreciated!
You need to change class ProjectsController < ActionController::Base to class ProjectsController < ApplicationController, then it will know where to search the layout.

rails 3.1.rc6 + factorygirl+ devise + spec2 => undefined method `Factory' for #<RSpec::Core::ExampleGroup::

my gem file looks like
source 'http://rubygems.org'
gem 'rails', '3.1.0.rc6'
gem 'sqlite3'
gem 'devise'
gem 'will_paginate'
gem 'therubyracer'
group :assets do
gem 'sass-rails', " ~> 3.1.0.rc"
gem 'coffee-rails', "~> 3.1.0.rc"
gem 'uglifier'
end
gem 'jquery-rails'
group :test do
gem 'turn', :require => false
gem 'rspec-rails'
gem 'webrat'
end
group :development do
gem 'rspec-rails'
gem 'webrat'
gem 'spork'
gem 'factory_girl_rails'
gem 'capybara'
gem 'guard-rspec'
end
my factories.rb
Factory.define :user do |user|
user.username "ccc"
user.email "ccc#eg.com"
user.password "foobar"
user.password_confirmation "foobar"
end
Factory.define :user_hero do |hero|
hero.supername "superman"
hero.association :user
end
my hero_controller_spec looks like this
require 'spec_helper'
describe HerosController do
include Devise::TestHelpers
render_views
before(:each) do
#user = Factory(:user)
# #request.env["devise.mapping"] = :user
# #user = Factory.create(:user)
sign_in #user
#hero_attr = {
:supername => "superman",
}
end
it "should create a new instance with valid attributes" do
#user.heros.create!(#hero_attr)
end
end
My autotest or guard shows up the following message
Failures:
1) HerosController should create a new instance with valid attributes
Failure/Error: #user = Factory(:user)
NoMethodError:
undefined method `Factory' for #<RSpec::Core::ExampleGroup::Nested_1:0x000001028a3998>
# ./spec/controllers/heros_controller_spec.rb:8:in `block (2 levels) in <top (required)>'
Finished in 0.00726 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/controllers/heros_controller_spec.rb:33 # HerosController should create a new instance with valid attributes
in spec_helper.rb
add the following
require 'factory_girl'
load 'factories.rb'
Try this:
#user.HerosController.create!(#hero_attr)
in place of:
#user.create!(#hero_attr)
Factory Girl needs to be in the test group otherwise it never gets loaded when you run your specs. Currently it's loaded only in your development group.
Try this
#user = FactoryGirl(:user)
or
#user = FactoryGirl.create(:user)