Ruby: Strange string comparison assertion behaviour - ruby

Can anyone explain what is happening here? I have this simple class with some static methods, and I want to test them.
yaqueline/build/converters/asciidocconverter.rb
# encoding: UTF-8
require 'asciidoctor'
module Yaqueline
module Build
module Converters
class AsciiDocConverter < Converter
class << self
def matches path
path =~ /\.(asciidoc|adoc|ascii|ad)$/
end
def convert content
html = Asciidoctor.convert content, to_file: false, safe: :safe
html = get_guts_out_of_body html
puts "asciidoc #{html}"
html
end
def get_guts_out_of_body html
if html =~ /<body>/
puts "get guts: #{html}"
return html.match(%r{(?<=<body>).*(?=</body>)})
end
html
end
end # class << self
end # class
end
end
end
and the test in test/build/converters/asciidocconverter_test.rb:
# encoding: utf-8
require 'helper'
require 'yaqueline/build/converters/asciidocconverter'
class TestAsciidocConverter < Test::Unit::TestCase
should "be able to get body html from a document" do
value = %q{SUCCESS}
html = %Q{
<html>
<head>
<title>Hej värld</title>
</head>
<body>#{value}</body>
</html>}
guts = Yaqueline::Build::Converters::AsciiDocConverter.get_guts_out_of_body html
puts "guts was '#{guts}'"
assert value.eql?(guts), "guts was '#{guts}', expected '#{value}'"
end
end
When running the test with
$ rake test TEST=test/build/converters/asciidocconverter_test.rb
The results looks good to me:
Started
get guts:
<html>
<head>
<title>Hej värld</title>
</head>
<body>SUCCESS</body>
</html>
guts was 'SUCCESS'
F
===============================================================================================================================================================================
Failure:
guts was 'SUCCESS', expected 'SUCCESS'.
<false> is not true.
test: AsciidocConverter should be able to get body html from a document. (TestAsciidocConverter)
/Users/mats/src/examples/yaqueline/test/build/converters/asciidocconverter_test.rb:37:in `block in <class:TestAsciidocConverter>'
/Users/mats/src/examples/yaqueline/test/build/converters/asciidocconverter_test.rb:39:in `instance_exec'
/Users/mats/src/examples/yaqueline/test/build/converters/asciidocconverter_test.rb:39:in `block in create_test_from_should_hash'
===============================================================================================================================================================================
but the assertion fails which seems odd to me and I'll need some help.
I'm running ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin15]
and my Gemfilelooks like
# Add dependencies required to use your gem here.
# Example:
# gem "activesupport", ">= 2.3.5"
gem 'mercenary'
gem 'safe_yaml'
gem 'kramdown'
gem 'colorator'
gem 'pathutil'
gem 'nokogiri'
gem 'sass'
gem 'listen', '~> 3.0'
gem 'asciidoctor'
gem 'tilt'
gem 'erubis'
# Add dependencies to develop your gem here.
# Include everything needed to run rake, tests, features, etc.
group :development do
gem "rdoc", "~> 3.12"
gem "bundler", "~> 1.0"
gem "juwelier", "~> 2.1.0"
gem "simplecov", ">= 0"
gem 'rubocop', '~> 0.48.1', require: false
gem 'thin' # or whatever I end up with
gem 'minitest'
gem 'test-unit'
gem 'shoulda'
end
Maybe this helps to realize hat test harness I'm using.
Can anyone see the mistake or explain what's going on?
Cheers

Inspect the types of values being compared. One of them is not a string. (Thus, it can't be equal to a string).
guts = html.match(%r{(?<=<body>).*(?=</body>)})
guts # => #<MatchData "SUCCESS">
guts.to_s # => "SUCCESS"

Related

Not sure why my rake seed file isn't running

here is my seed file :
require 'pry'
require 'rest-client'
require 'json'
require 'faker'
Consumer.delete_all
AlcoholicBeverage.delete_all
Intake.delete_all
100.times do
name = Faker::Name.first_name
sex= Faker::Gender.binary_type
weight= Faker::Number.between(from: 1, to: 10)
Consumer.create!(name:name,sex:sex,weight:weight)
end
ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
#ingredients_data=JSON.parse(ingredients)
#ingredients_data.collect do |x,y|
AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end
100.times do
consumer_id = rand(1..100)
alcoholic_beverage_id = rand(1..100)
Intake.create!(consumer_id: consumer_id, alcoholic_beverage_id:alcoholic_beverage_id)
end
here is my gemfile:
# frozen_string_literal: true
source "https://rubygems.org"
gem "activerecord", '~> 5.2'
gem "sinatra-activerecord"
gem "sqlite3", '~> 1.3.6'
gem "pry"
gem "require_all"
gem "faker"
gem 'rest-client'
I've already ran my migrations fine.. so I'm not sure why nothing is showing up when I enter rake db:seed into my terminal.
Any advice or help will be much appreciated. I've also tried including require 'faker' in my seed file as well but it didn't change a thing.
This alternative approach will help you avoid missing data, by not depending on your ids being from 1 to 100:
consumers = 100.times.map do
name = Faker::Name.first_name
sex= Faker::Gender.binary_type
weight= Faker::Number.between(from: 1, to: 10)
Consumer.create!(name:name,sex:sex,weight:weight)
end
ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
#ingredients_data=JSON.parse(ingredients)
beverages = #ingredients_data.map do |x,y|
AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end
100.times do
Intake.create!(consumer: consumers.shuffle.first, alcoholic_beverage: beverages.shuffle.first)
end

How do I merge two or more results from elasticsearch rails gem?

I'm trying to merge two elasticsearch results into one variable, here my code tries...
class SearchController < ApplicationController
def index
end
def advanced
#results = {}
if !params[:fast_search].empty?
#results[:features] = TestCases.search(params[:fast_search]).results
#results[:steps] = Steps.search(params[:fast_search]).results
#results[:examples] = Examples.search(params[:fast_search]).results
else
unless params[:feature].blank?
features = TestCases.search(query: { match: { function: params[:feature] } }).results
features_tag = Steps.search(query: { match: { tags: params[:tags] } }).results
#results[:features] = features + features_tag
end
unless params[:steps].blank? || params[:scenario].blank?
#results[:steps] = Steps.search(query: { match: { scenario: params[:scenario] } }).results
params[:steps].each do |step|
#results[:steps] += Steps.search(query: { match: { steps: step } }).results
end
#results[:steps] += Steps.search(query: { match: { tags: params[:tags] } }).results
end
unless params[:examples].blank?
params[:examples].each do |example|
#results[:examples] += Examples.search(query: { match: { examples: example } }).results
end
#results[:examples] += Examples.search(query: { match: { tags: params[:tags] } }).results
end
unless params[:bug].blank?
#results[:miscs] = StepsMiscs.search(query: { match: { bug: true } }).results
end
end
render "search/index"
end
end
I also try features.merge(features_tag) but no success either.
It's simple, I just need to merge one and more results from the elasticsearch, but I simply don't know how.
Here's my Gemfile:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# 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.2'
# 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 navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# jQuery-Turbolinks
gem 'jquery-turbolinks'
# Mysql
gem 'mysql2'
# Safe Attributes
gem 'safe_attributes'
# Elastic Search
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'elasticsearch-persistence'
gem 'pry'
#rake
gem 'rake'
#sidekiq
gem 'sidekiq'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platform: :mri
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console'
end
group :production do
#passenger
gem "passenger", require: "phusion_passenger/rack_handler"
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
And here's obviously the error that I'm getting:
undefined method `+' for #<Elasticsearch::Model::Response::Results:0x0000000d2719f8>
Thanks!
Here after a lot of search, I've found this:
unless params[:steps].blank? || params[:scenario].blank? || params[:tags].blank?
query = Jbuilder.encode do |json|
json.query do
json.match do
json.scenario do
json.query params[:scenario]
end
end
params[:steps].each do |step|
json.match do
json.tags do
json.query step
end
end
end
json.match do
json.tags do
json.query params[:tags]
end
end
end
end
#results[:steps] = Steps.search(query).results
end
This help me to search more than one match on all my models.
I know that catch only the basics, but at the moment is part for what I need and I hope this could help all the others around here with the same issue!
Thanks you all!

Rails 4, Strong Parameters, Unpermitted parameters on fields belonging to associated model

This is my first try at using models with associations with Rails 4 and for some reason I'm not able to get at the parameters POST'ed in due to a "Unpermitted parameters" error. I have tried to permit the associated fields several different ways with no success.
Basically, I have an Adoption Request with an associated Person.
class AdoptionRequest < ActiveRecord::Base
has_one :person
accepts_nested_attributes_for :person
end
and
class Person < ActiveRecord::Base
belongs_to :adoption_request
end
Here are the relevant sections from adoption_requests_controller.rb:
def create
#adoption_request = AdoptionRequest.new(adoption_request_params)
respond_to do |format|
if #adoption_request.save
format.html { redirect_to #adoption_request, notice: 'Adoption request was successfully created.' }
format.json { render action: 'show', status: :created, location: #adoption_request }
else
format.html { render action: 'new' }
format.json { render json: #adoption_request.errors, status: :unprocessable_entity }
end
end
end
private
def adoption_request_params
params.require(:adoption_request).permit(person_attributes: [:first_name, :last_name])
end
The form in the view is generated using rails-bootstrap-forms:
= bootstrap_form_for #adoption_request do |f|
= f.fields_for #adoption_request.person do |owner_fields|
= owner_fields.text_field :first_name
= owner_fields.text_field :last_name
= f.submit
Here is an example of the HTML generated by this for the first name field:
<input class="form-control" id="adoption_request_person_first_name" name="adoption_request[person][first_name]" type="text">
Now when I submit the following POST payload:
{"utf8"=>"✓", "authenticity_token"=>"kE1Q222VzXRsuLnhiO0X3mijW1TGTWSAOVgVDz/rxsE=", "adoption_request"=>{"person"=>{"first_name"=>"John", "last_name"=>"Smith"}}, "commit"=>"Create Adoption request"}
The adoption request is created, but the associated person is not. This is appears to be happening because strong parameters is not allowing the person parameters to come through. Case in point, I see this in the rails console output:
Unpermitted parameters: person
According to the strong parameters documentation, this configuration should work, but I have also tried:
params.require(:adoption_request).permit(:person, person_attributes: [:first_name, :last_name])
which results in the same error ("Unpermitted parameters: person"), and
params.require(:adoption_request).permit!
works to allow the parameters through, but this is not an acceptable solution as it negates the whole purpose of using strong parameters.
What am I doing wrong?
Here is my Gemfile, in case it is helpful:
source 'https://rubygems.org'
ruby '2.0.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# 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', '~> 1.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
# Use Bootstrap
gem 'bootstrap-sass', '~> 3.3.4'
# Use Figaro to make using environment variables easier
gem 'figaro'
# Use Slim templating engine
gem "slim-rails"
# User authlogic for authentication system
gem 'authlogic'
# Use rails-bootstrap-forms to integrate rails form builder with bootstrap
gem 'bootstrap_form'
group :test do
# use MiniTest::Spec::DSL
gem 'minitest-spec-rails', '~> 4.7'
end
The app itself is more complex than this. I've simplified it to illustrate the problem.
Thanks in advance for your help!
You need to change this line
= f.fields_for #adoption_request.person do |owner_fields|
to
= f.fields_for :person do |owner_fields|
I would simply try building the Person object on save. Pass the first and last names up as hidden fields.
Otherwise I would give strong parameters a read.
if #adoption_request.save
#adoption_request.persons.build(first_name: #first_name, last_name: #last_name)

getting wrong number argument error using Rails

Hi i am getting the following errors while using wicked_pdf gem in Rails3.
error:
ArgumentError in UsersController#download_pdf
wrong number of arguments (0 for 1)
Rails.root: C:/Site/generate4
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:6:in `download_pdf'
After clicking on download pdf link the following error is coming.
error-2:
RuntimeError in UsersController#download_pdf
Error: Failed to execute:
["C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe", "--encoding", "UTF-8", "file://C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-1192-1qf0ac.html", "C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf_generated_file20150527-1192-fijfxt.pdf"]
Error: PDF could not be generated!
Command Error: Loading pages (1/6)
[> ] 0%
[======> ] 10%
Error: Failed loading page file://c/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-1192-1qf0ac.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: ContentNotFoundError
Please check my code below.
users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
pdf=WickedPdf.new.pdf_from_string(
render_to_string pdf: "test.pdf", template: "users/test.html.erb", encoding: "UTF-8")
#save_path = 'C:\Site\download_pdf.pdf'
end
end
users/test.html.erb:
<h1>Hello rails</h1>
wicked_pdf.rb:
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => 'C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe'
}
Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.19'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'wicked_pdf'
My requirement is convert HTML to PDF using Rails 3.Please help me to resolve this error and successfully get the PDF file.
Assuming, you are trying to download the pdf file.
see the code below:
#users_controller.rb:
class UsersController < ApplicationController
def download_pdf
pdf = render_to_string(pdf: "test.pdf", template: "users/test.html.erb", encoding: "UTF-8")
send_data pdf
end
end
# Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.19'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'wicked_pdf', :github => 'mileszs/wicked_pdf', :branch => 'master'
Please check if it works.

Getting a wrong argument type RSpec::Matchers::Matcher (expected Proc) error in Rspec when testing responses in Rails

I am trying to test my Rails 3.0.9 controller with Rspec 2.6.4 and Webrat 0.7.3. My controller looks like this:
#metrics_controller.rb
class MetricsController < ApplicationController
def show
#metric = Metric.all(:msrun_id => params[:id]).first
end
def index
#metrics = Metric.all
end
end
And my controller spec looks like this:
#metrics_controller_spec.rb
require 'spec_helper'
describe MetricsController do
describe "GET #index" do
it "should be successful" do
get :index
response.should be_success
end
end
describe "GET show" do
it 'contains an overview of a metric' do
get :show, :id => 1
response.should have_selector('title', :content => "Metric Overview")
end
end
end
This looks very similar to other examples I have seen in documentation, but when I run bundle exec rspec spec/controllers/metrics_controller_spec.rb I am getting some strange errors:
1) MetricsController GET #index should be successful
Failure/Error: response.should be_success
TypeError:
wrong argument type RSpec::Matchers::BePredicate (expected Proc)
# ./spec/controllers/metrics_controller_spec.rb:8
2) MetricsController GET show contains an overview of a metric
Failure/Error: response.should have_selector('title')
TypeError:
wrong argument type Webrat::Matchers::HaveSelector (expected Proc)
# ./spec/controllers/metrics_controller_spec.rb:16
It looks like something weird is going on with the response.should method. If I change the first example to something more verbose that doesn't call should on response like this:
response.success?.should == true
then the example works fine, but why would should be expecting a Proc? Any ideas about how I can fix this?
This is not an especially helpful answer, but I will put it in here in case someone else gets stuck on the same thing. I inherited the project from someone else, and they set it up to use both railties and rails. Changing the Gemfile to look like this:
source 'http://rubygems.org'
RAILS_VERSION = '~> 3.0.7'
DM_VERSION = '~> 1.1.0'
gem 'railties', RAILS_VERSION, :require => 'rails'
gem 'activesupport', RAILS_VERSION
gem 'actionpack', RAILS_VERSION
gem 'actionmailer', RAILS_VERSION
gem 'dm-rails', DM_VERSION
gem 'rspec-rails'
#other gems below
Instead of something like this:
source 'http://rubygems.org'
gem 'rails'
gem 'dm-rails', '~> 1.1.0'
gem 'rspec-rails'
#other gems below
along with changing the config/application.rb to require the railties instead of rails seemed to fix it. The key seemed to be using railties instead of all of rails along with dm-rails.

Resources