POST method in ruby does not insert data into the table - ruby

I just started to learn programming. I study the book Jump start Sinatra by Darren Johnson.
I did everything as stated in the book, but insert a new entry in the table at me is not working. I click on the button "Save Song" but nothing happens.
At the same time modify existing records I can.
My main.rb
require 'sinatra'
require 'sinatra/reloader' if development?
require 'slim'
require 'sass'
require './song'
set :public_folder, 'public'
set :views, 'views'
get('/styles.css'){ scss :styles }
get '/' do
slim :home
end
get '/about' do
#title = "All About This Website"
slim :about
end
get '/contact' do
slim :contact
end
not_found do
slim :not_found
end
My song.rb
require 'dm-core'
require 'dm-migrations'
configure do
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")
end
class Song
include DataMapper::Resource
property :id, Serial
property :title, String
property :lyrics, Text
property :length, Integer
property :released_on, Date
def released_on=date
super Date.strptime(date, '%m/%d/%Y')
end
end
DataMapper.finalize
get '/songs' do
#songs = Song.all
slim :songs
end
get '/songs/new' do
#song = Song.new
slim :new_song
end
get '/songs/:id' do
#song = Song.get(params[:id])
slim :show_song
end
post '/songs' do
song = Song.create(params[:song])
redirect to("/songs/#{song.id}")
end
get '/songs/:id/edit' do
#song = Song.get(params[:id])
slim :edit_song
end
put '/songs/:id' do
song = Song.get(params[:id])
song.update(params[:song])
redirect to("/songs/#{song.id}")
end
My views/song_form.slim
label for="title" Title:
input#title type="text" name="song[title]" value="#{#song.title}"
label for="length" Length:
input#length type="number" name="song[length]" value="#{#song.length}"
label for="released_on" Date(mm/dd/yyyy):
input#released_on type="text" name="song[released_on]" value="#{#song.released_on.strftime("%m/%d/%Y") if #song.released_on}"
label for="lyrics" Lyrics:
textarea#lyrics name="song[lyrics]" == #song.lyrics
input type="submit" value="Save Song"
My views/edit_song.slim
h1 Edit Song
form method="POST" action="/songs/#{#song.id}"
input type="hidden" name="_method" value="PUT"
== slim :song_form
When I try to add a new table record in IRB:
irb(main):001:0> require './song'
NoMethodError: undefined method `get' for main:Object
from /media/kamrenov/other/work/sinatra/song.rb:21:in `<top (required)>'
from /home/kamrenov/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/kamrenov/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from (irb):1
from /home/kamrenov/.rbenv/versions/2.2.1/bin/irb:11:in `<main>'

Related

Getting Frozen Error-Can't modify frozen string

Getting frozen error while running below mentioned cod. Also find the helpers files. Below is the main file:
require 'spec_helper.rb'
require 'rspec_capybara_assignment_helper.rb'
describe 'Open the automationpractices site' , :type => :request do
it 'Test: Page Content', :page do
visit "http://automationpractice.com/index.php"
expect(page).to have_xpath(".//img[contains(#src,'automationpractice.com/img/logo')]")
expect(page).to have_xpath(".//input[#id='search_query_top']")
expect(page).to have_link("Contact us")
expect(page).to have_link("Sign in")
within('div#block_top_menu') do
expect(page).to have_link("Women")
expect(page).to have_link("Dresses")
expect(page).to have_link("T-shirts")
end
within('div#center_column') do
expect(page).to have_link("Popular")
expect(page).to have_link("Best Sellers")
end
expect(page).to have_content("Automation Practice Website")
end
end
Spec_Helper file:-spec_helper.rb
require 'rspec'
require 'capybara/rspec'
require 'capybara/dsl'
require "selenium-webdriver"
require "capybara"
require 'capybara/rspec/matchers'
RSpec.configure do |config|
config.include Capybara::DSL , :type => :request # to include capybara DSL methods
config.include Capybara::RSpecMatchers,:type => :request # to include Rspec matchers available.
end
Capybara.configure do |config|
config.run_server = false
config.default_driver = :selenium # which driver to use (selenium / chrome /internet explorer)
config.default_selector = :css #(by default css selector) # if user want to use xpath, he has to write find(:xpath, <xpath>).click
config.app_host = "http://automationpractice.com/index.php" # host app
config.default_max_wait_time = 5 # wait for 4 seconds.
config.app_host = #url
config.ignore_hidden_elements = true # will ignore hidden elements on page.
config.match =:prefer_exact # check for exact match.
end
Rspec Capybara Assignmnet Helper File:
rspec_capybara_assignment_helper.rb
def click_on(value)
find(value).click
end
def link_click(value)
click_link(value)
end
def button_click(value)
click_button(value)
end
def login_application
link_click('Sign in')
fill_in('email', :with => 'test.test#testing.com')
fill_in('passwd', :with => 'testtest')
button_click('SubmitLogin')
end
def sign_out
link_click('Sign out')
end
def search_product(value)
fill_in('search_query_top', :with => value)
button_click('Search')
sleep(2)
end
def add_product(value)
page.find(:css,'.product-image-container').hover
sleep(2)
first("a", :text => "More").click
sleep(4)
fill_in('quantity_wanted', :with => '2', visible: false)
select('M', :from => 'group_1')
find('button.exclusive').click
sleep(2)
first("span", :text => "Continue shopping", wait: 3).click
sleep(2)
end
def check_locator(value)
expect(page).to have_selector(value)
end
Error as below:
Open the automationpractices site
Test: Page Content (FAILED - 1)
Failures:
Open the automationpractices site Test: Page Content
Failure/Error: visit "http://automationpractice.com/index.php"
FrozenError:
can't modify frozen String
./spec/tests/rspec_capybara_assignment.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0.7789 seconds (files took 3.61 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/tests/rspec_capybara_assignment.rb:5 # Open the automationpractices site Test: Page Content
This appears to be related to selenium-webdriver, not capybara itself.
There's an issue about this at https://github.com/SeleniumHQ/selenium/issues/7365
To fix, specify in your gemfile that you want 3.142.4 as a minimum: gem 'selenium-webdriver', '~> 3.142.4'
And then run bundle update selenium-webdriver
That should get this specific issue resolved.

Cannot load such file in Test-Unit Sinatra

Im currently writing my test cases using ruby sinatra and im having a very weird or just im missing an important note/tip when writing a test cases using Test-Unit sinatra.
My problem is my my environments.rb is not being loaded in my test from my app.rb. but if i run it, it does get loaded.
here is my app.rb
require 'rubygems'
require 'sinatra'
require 'pg'
require './config/environments'
require './models/user'
module Registration
class HelloWorldApp < Sinatra::Base
helpers do
include Rack::Utils
alias_method :h, :escape_html
end
get '/' do
#title = " Introduction Biatch"
erb :index
end
post '/register' do
DB[:users].insert(username: params[:username],password: params[:password])
redirect '/view'
end
get '/view' do
#users = User.all
erb :view
end
get '/view/:id' do
#user = User.find(id: params[:id])
erb :edit
end
post '/edit/:id' do
#user = User.find(id: params[:id])
#user.update(username: params[:username],password: params[:password])
redirect '/view'
end
get '/delete/:id' do
#delete_user = User.find(id: params[:id])
#delete_user.delete
redirect '/view'
end
end
end
my environments.rb is in the config folder.
and here is my sample test cases. (not yet finished)
require 'rubygems'
require 'test/unit'
require 'test/unit/assertions'
require '../app/app'
module Registration
class TestCrud < Test::Unit::TestCase
# include Registration::HelloWorldApp
def test_insert_user
end
def test_get_all_user
end
def test_delete_all_user
end
end
end
and this is the error it throws.
C:/Ruby22-x64/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- ./config/environments (LoadError)
from C:/Ruby22-x64/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from C:/Users/John/Documents/Sinatra-Intro/app/app.rb:4:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from C:/Ruby22-x64/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from test_crud.rb:4:in `<main>'
C:\Users\John\Documents\Sinatra-Intro\test>
Im very confused what did i do wrong. thanks in advance.
Ive found the answer, just change the require './config/environments' to require_relative. and change the require '../app/app' into require_into.

Why am I getting FactoryGirl wrong number of arguments error?

Having strange behavior from FactoryGirl in non-rails app. getting wrong number of arguments error...don't know why.
gideon#thefonso ~/Sites/testing (master)$ rspec spec
/Users/gideon/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-4.1.0/lib/factory_girl/syntax/default.rb:6:in `define': wrong number of arguments (1 for 0) (ArgumentError)
from /Users/gideon/Sites/testing/spec/factories.rb:1:in `<top (required)>'
Here are the files involved...
login_user_spec.rb
require_relative '../spec_helper'
require_relative '../lib/login_user'
describe "Existing User Log in Scenario", :type => :request do
before :all do
#user = FactoryGirl(:user)
end
xit "should allow user to select login from top nav" do
visit "/"
within("#main-header")do
click_link 'Log In'
end
page.should have_content('Log in to your account')
end
it "and fill in login form" do
visit "/login"
within("#login-form")do
fill_in 'user-email', :with => #user.email
fill_in 'user-password', :with => #user.password
end
#FIXME - the design crew will make this go away
within("#login-form") do
click_link '#login-link' #this gives false failing test...geek query...why?
end
page.should have_content('Manage courses')
end
end
Factories.rb
FactoryGirl.define :user do |u|
u.email "joe#website.com"
u.password "joe009"
end
user.rb
class User
attr_accessor :email, :password
end
spec_helper.rb
require 'rubygems'
require 'bundler/setup'
require 'capybara'
require 'rspec'
require 'capybara/rspec'
require 'json'
require 'capybara/dsl'
# Capybara configuration
Capybara.default_driver = :selenium
Capybara.app_host = "http://www.website.com"
require 'factory_girl'
# give me ma stuff
FactoryGirl.find_definitions
require "rspec/expectations"
include Capybara::DSL
include RSpec::Matchers
ANSWER: :user is a reserved word..changed it to :stuff...works fine now.
Try to use new syntax from readme
FactoryGirl.define do
factory :user do
email "joe#website.com"
password "joe009"
end
end
If this is a non-rails app you will have to create a Userclass first. I'm not sure if you have to have instance vars with name, password and email but you definitely will have to have that class defined somewhere.
See the Getting Started file on Github for more on that.
Try this
FactoryGirl.define do
factory :user do |u|
u.email "joe#website.com"
u.password "joe009"
end
end

Is there a way with test::unit Ruby to load gems

I am trying to use test::unit for testing and the framework I am trying to test requires a particular gem (rhodes)
Can anyone suggest how I can get the gem loaded when I run my tests
Update :: Error Message
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- rho (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from ../../app/Settings/controller.rb:1
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from ../test_helper.rb:4
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from test_settings.rb:4
My unit test uses require to include test_helper.rb which contains following
$: << "../../app"
require 'rubygems'
require 'rhodes'
require 'test/unit'
require 'Settings/controller'
Settings/controller lives in app and contains
require 'rho'
require 'rho/rhocontroller'
require 'rho/rhoerror'
require 'helpers/browser_helper'
class SettingsController < Rho::RhoController
include BrowserHelper
def index
#msg = #params['msg']
render
end
def login
#msg = #params['msg']
render :action => :login, :back => '/app'
end
def login_callback
errCode = #params['error_code'].to_i
if errCode == 0
# run sync if we were successful
WebView.navigate Rho::RhoConfig.options_path
SyncEngine.dosync
else
if errCode == Rho::RhoError::ERR_CUSTOMSYNCSERVER
#msg = #params['error_message']
end
if !#msg || #msg.length == 0
#msg = Rho::RhoError.new(errCode).message
end
WebView.navigate ( url_for :action => :login, :query => {:msg => #msg} )
end
end
def do_login
if #params['login'] and #params['password']
begin
SyncEngine.login(#params['login'], #params['password'], (url_for :action => :login_callback) )
render :action => :wait
rescue Rho::RhoError => e
#msg = e.message
render :action => :login
end
else
#msg = Rho::RhoError.err_message(Rho::RhoError::ERR_UNATHORIZED) unless #msg && #msg.length > 0
render :action => :login
end
end
def logout
SyncEngine.logout
#msg = "You have been logged out."
render :action => :login
end
def reset
render :action => :reset
end
def do_reset
Rhom::Rhom.database_full_reset
SyncEngine.dosync
#msg = "Database has been reset."
redirect :action => :index, :query => {:msg => #msg}
end
def do_sync
SyncEngine.dosync
#msg = "Sync has been triggered."
redirect :action => :index, :query => {:msg => #msg}
end
end
Edit 2: after looking at your code, I believe the following should work:
Move the lines from test_helper
require 'rubygems'
require 'rhodes'
to the very top of Settings/controller
Or are you thinking of loading it dynamically during setup/teardown (possibly to avoid conflicting dependencies etc.)?
Edit: I wrote up a quick example of testing a simple wrapper around a Watir class (UI manipulator for IE browser).
require 'rubygems'
require 'watir'
require 'test/unit'
class WatirWrapper
def initialize()
#browser = Watir::IE.new()
end
def method_missing(sym, *args, &block)
#browser.send(sym, *args, &block)
end
end
class WatirWrapperTest < Test::Unit::TestCase
def test_goto
#ww = WatirWrapper.new()
#ww.goto('http://www.google.com/')
assert_equal('http://www.google.com/', #ww.url())
end
end

Sinatra Mongoid String not valid UTF-8

I wrote this little application :
require 'rubygems'
require 'sinatra'
require 'bson'
require 'mongoid'
Mongoid.configure do |config|
name = "articles"
host = "localhost"
config.master = Mongo::Connection.new.db(name)
config.persist_in_safe_mode = false
end
class Article
include Mongoid::Document
field :title
field :content
end
get '/' do
#articles = Article.all
end
get '/show/:id' do
#article = Article.find(params[:id])
end
get '/new' do
haml :new
end
post '/create' do
#article = Article.new(params['article'])
if #article.save
redirect '/'
else
redirect '/new'
end
end
The following error occur when i post an article with a content "Test d'un article en français"
BSON::InvalidStringEncoding at /create String not valid UTF-8
How i can fix this error ?
Thanks
This is a known issue with Ruby 1.9 and Sinatra. Wait for Sinatra 1.1 to be released or use Sinatra edge version from github.

Resources