Cucumber wont find my step based on outline scenario - ruby-on-rails

I'm trying to make a simple test witch is capybara go to page, fill a field based on scenery, and verify if i have some text in page (i know this is a useless test but is just a POC), but cucumber wont find my step for get the example data and looks for a static step. here is the files
.feature:
Given que eu estou na página
When eu escrever no campo o nome <name>
Then deve ver receber a mensagem "Back"
scenary:
| name |
| wolo |
| xala |
the step:
When /^eu escrever no campo o nome "(.*?)"$/ do |name|
fill_in "usuario_nome", :with=> name
end
this is my log:
You can implement step definitions for undefined steps with these snippets:
When("eu escrever no campo o nome wolo") do
pending # Write code here that turns the phrase above into concrete actions
end
When("eu escrever no campo o nome xala") do
pending # Write code here that turns the phrase above into concrete actions
end

It's not finding your step because your step specifies "s are required but when you call it in your scenario there are no quotes. You either need to change you test to have
When eu escrever no campo o nome "<name>"
or change your step definition to
When /^eu escrever no campo o nome (.*?)$/ do |name|
fill_in "usuario_nome", :with=> name
end
Note: if using an up to date version of Cucumber you could also define your step using cucumber expressions which would be
When "eu escrever no campo o nome {string}" do |name|
fill_in "usuario_nome", :with=> name
end

Related

How to render images from Markdown files with Rails 5.2?

I based my applications inline help on Markdown files, implemented with Redcarpet gem. Contextual help is displayed as expected, but embedded images are not.
The help files structure in the project is:
public/help/administration/Connection
- Business_resources_hierarchy.png
- connections-fr.md
The connection-fr.md files contains:
# CONNECTIONS
Décrit la gestion des connexions aux ressources de l'infrastructure informatique.
## Principe de fonctionnement
La connaissance des ressources techniques comporte un certain niveau de complexité :
* adresses IP et protocoles des services
* login et mot de passe des utilisateurs techniques
* droits d'utilisation de la ressource
* multipliés par le nombre d'environnements déployés dans l'organisation (Dev, Test, Prod ...)
La gestion des connexions permet au métier de s'affranchir de cette complexité en offrant une vue métier des ressources nécessaires à la production statistique au travers d'une hiérarchie :
![Hiérarchie des resources métiers](Business_resources_hierarchy.png)
## Eléments d'infrastructure
1. Les ressources métiers - offrent une vue fonctionnelle des
Markdown is supported by the application_helper.rb:
module ApplicationHelper
### Implementing Help files management with Markdown
def markdown
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, tables: true)
end
def displayHelp
puts "Help requested for: #{params[:page_name]}.#{params[:format]}"
# Parse the request from the page -> namespace/class/controller
if params[:page_name].index('/')
domain = params[:page_name].split('/')[0]
page = params[:page_name].split('/')[1]
else
domain = ''
page = params[:page_name]
end
method = params[:format] # The method from the controller is not used yet
# Build the help file path and name using the current locale
case page
when 'Change_Log' # Does it still exist?
filename = File.join(Rails.root, 'public', "CHANGELOG.md")
when 'Release_notes' # Does it still exist?
filename = File.join(Rails.root, 'public', "Release_notes.md")
else
filename = File.join(Rails.root,
'public',
'help',
domain,
page.classify,
"#{page}-#{I18n.locale.to_s[0,2]}.md"
)
end
puts "Requested help file: #{filename}"
if not File.file?(filename)
filename = File.join(Rails.root, 'public', 'help', "help-index-#{I18n.locale.to_s[0,2]}.md")
end
begin
file = File.open(filename, "rb")
markdown.render(file.read).html_safe.force_encoding('UTF-8')
rescue Errno::ENOENT
render :file => "public/404.html", :status => 404
end
end
end
I tried a few ways to define the path to the image file, but it does not show up. When submitting the file URL to Rails, it raises the following error:
No route matches [GET] "/Business_resources_hierarchy.PNG"
How to define the path to the file, or configure the helper so that the image is displayed?

Rspec and Rails 4, update skip callback

I try to run an update test with rspec for my rails application.
I'm using rspec 3.5 and rails 4.
The behaviour is supposed to be the following :
When i create a new service with a selling price, it's create a Price instance and set the relation with the service. Then, when i update my service, if there is no selling price, it's destroy the price record (requirement of the client to save space in database).
The process i implemented seems to be working fine, when i test with the UI and i check the count of Price record, it's decrease by one like it's suppose. However, the unit test if failing.
Here is the code :
Service Controller :
def update
#service.assign_attributes(service_params)
puts "update method"
respond_to do |format|
if #service.valid?
if params['preview']
#service.build_previews
format.js { render 'services/preview' }
else
#service.save!
format.html { redirect_to client_trip_days_path(#client, #trip), notice: t('flash.services.update.notice') }
end
else
format.html { render :edit }
format.js { render :new }
end
end
end
The callback in the Service model :
def create_or_update_price
puts "in create or update price"
if selling_price.present? && price.present?
self.price.update_columns(:trip_id => trip.id, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif selling_price.present? && !price.present?
self.price = RegularPrice.create(:trip => trip, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif !selling_price.present? && price.present?
self.price.destroy
end
end
The test :
it "updates the lodging and destroy the price" do
puts "nombre de service avant création : "
puts Service.count
puts "nombre de prix avant création : "
puts Price.count
lodging = FactoryGirl.create(:lodging_service, selling_price: 200)
puts "nombre de service après création : "
puts Service.count
puts "nombre de prix après création : "
puts Price.count
expect(lodging.reload.price).to be_present
puts "nombre de prix avant update : "
puts Price.count
puts "id"
puts lodging.id
patch :update, client_id: client.id, trip_id: trip.id, id: lodging.to_param, service: valid_attributes_no_more_price
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_with_price
puts "nombre de prix après update : "
puts Price.count
# expect{
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_no_more_price
# }.to change(RegularPrice, :count).by(0)
expect(lodging.reload.price).to be_nil
end
let(:valid_attributes_no_more_price) {
attributes_for(:lodging_service, trip: trip, selling_price: "")
}
As you can see, there is a lot of puts since i try to find what is wrong.
The output is :
nombre de service avant création :
0
nombre de prix avant création :
0
in create or update price
nombre de service après création :
1
nombre de prix après création :
1
nombre de prix avant update :
1
id
10
nombre de prix après update :
1
Failure/Error: expect(lodging.reload.price).to be_nil
expected: nil
got: #<RegularPrice id: 2, label: nil, currency: "CHF", selling_price: 200.0, priceable_type: "Service", p...ated_at: "2017-07-13 08:08:47", quantity: 1, type: "RegularPrice", position: 1, purchase_price: nil>
As we can see, it's look like the callback is not fired after the update, and the action in the controller is not reached.
Have you any idea what is going wrong?
Thanks :)
PS: I always have trouble to include code in my questions, is there a tutorial on how to make it?
Since you did not mentioned your ruby version I'll assume it's 2.
First of all you need to learn how to properly debug your code in order to fix the issues yourself.
Here is what you have to do:
1.Add pry gem to your app, pry-byebug there is also a version for ruby 1.9.3.
2.Add a break point in your code
it "updates the lodging and destroy the price" do
(...) # Code here.
binding.pry # The debugger will open a console at this point
(...) # Maybe more code here
end
3.Verify all the variable and their values and see where the problem lies
In case you could not find the issue with binding.pry in your rspec file before the expect add it to after the first line of the method, and you can step through the debugger by typing next in the console opened by pry (it will be where your rails server is runnig).
If that still does not help, try and add a binding.pry in your classes and see what is the state in there.
Spend a few minutes/hours now to learn debugging and it will save you days/weeks in long term. (while you are learning you don't really know how a program should behave and that extra knowledge is priceless, after a while you only need a debugger for extremely complicated issues).

Devise Internationalization

I have setup Devise for my application and have created an fr.yml file in my locales folder in order to get error messages translated.
Here is my fr.yml file at the moment.
fr:
activerecord:
attributes:
client:
password: "Mot de passe"
email: "Email"
password_confirmation: "Confirmation du mot de passe"
remember_me: "Se souvenir de moi"
log_in: "Connection"
errors:
models:
client:
attributes:
password_confirmation:
confirmation: "Confirmation du mot de passe"
(It is pretty sketchy at the moment but I will develop it later on. )
Though a fun thing is happening: when I try to create a new user of the client model and let's say I forget to input the password confirmation, Devise returns the following error :
"Confirmation du mot de passe Confirmation du mot de passe"
It seems the error message is duplicated.
I have removed all French translations for 'password_confirmation' in my fr.yml file and got the following error :
"Password confirmation translation missing: fr.activerecord.errors.models.client.attributes.password_confirmation.confirmation"
Not sure what I can do to get the fr.yml right
I honestly don't know exactly why this is happening but you aren't following Devise localization standards.
Please check devise fr.yml from Devise-i18n project here : https://github.com/tigrish/devise-i18n/blob/master/rails/locales/fr.yml - you don't have to install the gem -.

Cucumber steps definitions in spanish: Ambiguous match of "..."

I'm trying to translate the steps definitions of cucumber to spanish but I'm getting this error:
Ambiguous match of "que estoy en la página "inicio de sesión""
features/step_definitions/web_steps.rb:3:in `/^que estoy en la página "([^"]*)"$/'
features/step_definitions/web_steps.rb:7:in `/^visito la pa|ágina "([^"]*)"$/'
Here's my web_steps.rb
# encoding: utf-8
Dado /^que estoy en la página "([^"]*)"$/ do |page|
visit(path_to page)
end
Cuando /^visito la página "([^"]*)"$/ do |page|
visit(path_to page)
end
How can that be ambiguos if I got the ^ and the $ in the regexp?
It looks like it's seeing a | in the latter step definition. Look closely at the second line of the error:
features/step_definitions/web_steps.rb:3:in `/^que estoy en la página "([^"]*)"$/'
features/step_definitions/web_steps.rb:7:in `/^visito la pa|ágina "([^"]*)"$/'
It's seeing /^visito la pa|ágina "([^"]*)"$/, which it interprets as an OR, i.e. /^visito la pa OR ágina "([^"]*)"$/. With that interpretation, the match does indeed become ambiguous.
Now why it is reading it that way is a mystery to me, perhaps some UTF-8 garbling?

Rails Model.save get datetime convertion error: "A conversão de um tipo de dados varchar em um tipo de dados..."

I've a problem with SQL Server and Rails.
Rails and SQL Server seems to save date format in different ways:
Rails way: 2011-12-15
SQL Server: 15-12-2011
As I'm running SQL Server in Brazilian Portuguese so my problem might exist only for brazilian people.
Whenever I do any Model.save on Rails, I'm getting this error:
A conversão de um tipo de dados varchar em um tipo de dados
datetime resultou em um valor datetime fora do intervalo.: <my query here>
As Rails insert/update the created_at and updated_at columns, I always get this error.
Does anyone knows how to solve this?
I'm running jRuby on activerecord-jdbcmssql-adapter.
it's dead simple...just create a file under config/initializer with the name you want, I use datetime_format.rb. With this line:
Time::DATE_FORMATS[:db]= '%d-%m-%Y %H:%M:%S'
This will overwrite the default datetime format for the DB.
Just found a solution:
I've created a file named "sqlserver_dateformat.rb" in Rails' lib/ folder and added this:
class ActiveRecord::Base
before_save :set_sqlserver_dateformat
def set_sqlserver_dateformat
ActiveRecord::Base.connection.exec_query("set DATEFORMAT ymd")
end
end
Now on everymodel I've required it:
require 'sqlserver_dateformat'
class User < ActiveRecord::Base
# ...
end
I known, it's a monkey patch, but hey, it works! =]

Resources