unsupported: Symbol in Cucumber on Rails - ruby-on-rails

I am trying to call each on an ActiveRecord object/list in RoR as shown in the following chunk of code.
41 Then /I should (not )?see movies with ratings: (.*)/ do |not_see, rating_li>
42 #movies = Movie.where(:rating, rating_list.split(", "))
43 rating_list.split(",").map do |x|
44 x.strip
45 end.each do |rating|
46 if not_see
47 #movies.each do |movie|
48 #movie.title
49 end
50 else
51 puts "hello"
52 end
53 end
54 end
And this produces the following error message:
And I should not see movies with ratings: G, PG-13, NC-17 # features/step_definitions/movie_steps.rb:41
unsupported: Symbol (RuntimeError)
./features/step_definitions/movie_steps.rb:47:in `block (2 levels) in <top (required)>'
./features/step_definitions/movie_steps.rb:45:in `each'
./features/step_definitions/movie_steps.rb:45:in `/I should (not )?see movies with ratings: (.*)/'
features/filter_movie_list.feature:33:in `And I should not see movies with ratings: G, PG-13, NC-17'
Removing line 47 in the code above gets rid of the error. Why is that? As far as I can tell, all of these are valid Ruby code. What am I missing?
Thank you all!

The line of code that was causing the error is line 42. The call to where should have been:
Movie.where(:rating => rating_list.split(","))
"=>" and not ","

Related

ruby / rails: TypeError: can't convert Symbol into Integer

I'm trying to update my Representation attributes ivpn & idirect (from a csv file via rake task but i just print here only the meat of the program) and getting the TypeError:
# in Rails Console:
representation = Representation.where(id: 977)
# => Representation_id: 977, ivnp: false, idirect: false
rows = Hash.[:ivpn => "", :idirect => "x"] # originally rows are coming from csv-file
representation.update_attributes! ivpn: rows.any?{|r| r[:ivpn].present?}, idirect: rows.any? {|r| r[:idirect].present?}
TypeError: can't convert Symbol into Integer
from (irb):42:in `[]'
from (irb):42:in `block in irb_binding'
from (irb):42:in `each'
from (irb):42:in `any?'
What I'm missing here?
try this:
representation.update_attributes! ivpn: rows.any?[{|r| r[:ivpn].present?}], idirect: rows.any? [{|r| r[:idirect].present?}]

RSPEC - Expected vs Received Error

Here is my test:
describe Item do
subject {Item.new(:report_id => 26 , :name => 'Gas' , :tax_rate => 0.13, :tax_id => 1 , :category_id => 15 , :sub_category_id => 31 , :job_id => 1 , :total => 20 )}
let(:tax) {Tax.where(id: subject.tax_id).first}
let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first}
it 'Calculate with just Total' do
subject.name.should be == 'Gas'
tax = Tax.find_by_id(subject.tax_id)
subject.sub_category_id.should be == 31
subject.set_nil_values
sub_category.should_receive(:taxable).and_return(1)
tax.should_receive(:rate).and_return(0.13)
sub_category.should_receive(:tax_adjustment).and_return(nil)
subject.should_receive(:tax_rate).and_return(0.13)
subject.calculate_tax(tax, sub_category)
subject.tax_amount = (((subject.total - subject.deduction) - ((subject.total - subject.deduction) / (1 + 0.13))) * 1)
subject.calculate_cost
subject.cost.should be_within(0.01).of(17.70)
end
Here is my error:
1) Item Calculate with just Total
Failure/Error: subject.should_receive(:tax_rate).and_return(0.13)
(#<Item:0x007faab7299c30>).tax_rate(any args)
expected: 1 time with any arguments
received: 3 times with any arguments
# ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>'
I did some research, and tried to use this instead:
expect_any_instance_of(subject).to receive(:tax_rate)
But now get the following error:
1) Item Calculate with just Total
Failure/Error: expect_any_instance_of(subject).to receive(:tax_rate)
NoMethodError:
undefined method `method_defined?' for #<Item:0x007fe6fdaa1bf8>
# ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>'
Your initial error occurred because, as the error message stated, the method in question was called three times rather than once, which is the implicit expectation. Assuming the actual behavior is what it should be, you can change the expectation to be:
...receive(...).exactly(3).times
See http://rubydoc.info/gems/rspec-mocks/frames for more info.
As for the second error you encountered, based on my testing, this occurs when you use expect_any_instance_of with a class that already has an instance stubbed and then you call that stubbed instance. In any event, even if this had worked, I don't believe it's what you would have wanted, as the semantics in terms of frequency of expect_any_instance_of is the same as expect, namely "one (total) call across the stubbed instance(s)".
If this second error occurred without you having removed the existing expectation on subject, let me know.

NoMethodError in Human_resources/leaves#index

It was working few days ago, don't know what had went wrong...
**undefined method `name' for nil:NilClass**
Extracted source (around line #26):
23: %td= number_with_precision(employee.compensation_leave_balance, precision:1)
24: #calendar.tab-pane.fade
25: = calendar(:year => 2012, :month => 6, :first_day_of_week => 1, summary: "Leave Calendar", calendar_title: "June", month_header: true) do |date|
26: - render_leave_calendar_cell(date)
27: #trash.tab-pane.fade
28: = render 'table', leaves: #leaves.where(deleted: true)
app/helpers/leaves_helper.rb:11:in `block in events_for'
app/helpers/leaves_helper.rb:10:in `events_for'
app/helpers/leaves_helper.rb:4:in `render_leave_calendar_cell'
app/views/human_resources/leaves/index.html.haml:26:in `block in _app_views_human_resources_leaves_index_html_haml__145883348_88978910'
app/helpers/calendar_helper.rb:146:in `call'
app/helpers/calendar_helper.rb:146:in `block in calendar'
app/helpers/calendar_helper.rb:145:in `upto'
app/helpers/calendar_helper.rb:145:in `calendar'
app/views/human_resources/leaves/index.html.haml:25:in `_app_views_human_resources_leaves_index_html_haml__145883348_88978910'
really don't know what went wrong
a/h/leaves_helper.rb
1 module LeavesHelper
2 def render_leave_calendar_cell(date)
3 html = content_tag(:span, date.day, class: 'dayDisplay')
4 html += content_tag(:div, events_for(date))
5 raw(html)
6 end
7
8 def events_for(date)
9 html = ""
10 current_company.leaves.where("start_date <= '#{date}' and return_date > '#{date}'").where(deleted: false).each do |leave|
11 html += content_tag(:div, leave.applicant.name, class: 'leaveName')
12 end
13 raw html
14 end
could it be the date nil? how to fix this ><
much appreciate
Billy
as abhas already stated, leave.applicant is nil for at least one of the leaves.
go to your database and find out which it is. then figure out what to do with your leaves. delete them too, re-add the missing applicant or what ever data migration might be sensible.
a quick fix would be to skip if an applicant is missing:
html += content_tag(:div, leave.applicant.name, class: 'leaveName') if leave.applicant.present?
i would also have a look if you properly configured the delete cascades in your application. this often causes such problems. if you want to enforce safety in this regard, you should add database constraints, that ensure that no referenced entity gets deleted.

How to count lines of code?

I tried rake stats but that seems highly inaccurate. Perhaps it ignores several directories?
I use the free Perl script cloc. Sample usage:
phrogz$ cloc .
180 text files.
180 unique files.
77 files ignored.
http://cloc.sourceforge.net v 1.56 T=1.0 s (104.0 files/s, 19619.0 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Javascript 29 1774 1338 10456
Ruby 61 577 185 4055
CSS 10 118 133 783
HTML 1 13 3 140
DOS Batch 2 6 0 19
Bourne Shell 1 4 0 15
-------------------------------------------------------------------------------
SUM: 104 2492 1659 15468
-------------------------------------------------------------------------------
Here's a simple solution. It counts the lines of code in your rails project's app folder - CSS, Ruby, CoffeeScript, and all. At the root of your project, run this command:
find ./app -type f | xargs cat | wc -l
EDIT
Read the comments. Then try this instead:
find ./app -type f -name "*.rb" | xargs cat | sed "/^\s*\(#\|$\)/d" | wc -l
You can try out these two options:
Hack rake stats
Rakestats snippet from blogpost:
namespace :spec do
desc "Add files that DHH doesn't consider to be 'code' to stats"
task :statsetup do
require 'code_statistics'
class CodeStatistics
alias calculate_statistics_orig calculate_statistics
def calculate_statistics
#pairs.inject({}) do |stats, pair|
if 3 == pair.size
stats[pair.first] = calculate_directory_statistics(pair[1], pair[2]); stats
else
stats[pair.first] = calculate_directory_statistics(pair.last); stats
end
end
end
end
::STATS_DIRECTORIES << ['Views', 'app/views', /\.(rhtml|erb|rb)$/]
::STATS_DIRECTORIES << ['Test Fixtures', 'test/fixtures', /\.yml$/]
::STATS_DIRECTORIES << ['Email Fixtures', 'test/fixtures', /\.txt$/]
# note, I renamed all my rails-generated email fixtures to add .txt
::STATS_DIRECTORIES << ['Static HTML', 'public', /\.html$/]
::STATS_DIRECTORIES << ['Static CSS', 'public', /\.css$/]
# ::STATS_DIRECTORIES << ['Static JS', 'public', /\.js$/]
# prototype is ~5384 LOC all by itself - very hard to filter out
::CodeStatistics::TEST_TYPES << "Test Fixtures"
::CodeStatistics::TEST_TYPES << "Email Fixtures"
end
end
task :stats => "spec:statsetup"
metric_fu - A Ruby Gem for Easy Metric Report Generation
PS: I haven't tried any of the above, but metric_fu sounds interesting, see the screenshots of the output.
This one calculates number of files, total lines of code, comments, and average LOC per file. It also excludes files inside directories with "vendor" in their name.
Usage:
count_lines('rb')
Code:
def count_lines(ext)
o = 0 # Number of files
n = 0 # Number of lines of code
m = 0 # Number of lines of comments
files = Dir.glob('./**/*.' + ext)
files.each do |f|
next if f.index('vendor')
next if FileTest.directory?(f)
o += 1
i = 0
File.new(f).each_line do |line|
if line.strip[0] == '#'
m += 1
next
end
i += 1
end
n += i
end
puts "#{o.to_s} files."
puts "#{n.to_s} lines of code."
puts "#{(n.to_f/o.to_f).round(2)} LOC/file."
puts "#{m.to_s} lines of comments."
end
If your code is hosted on GitHub, you can use this line count website. Just enter your GitHub URL and wait for the result.
Example for Postgres: https://line-count.herokuapp.com/postgres/postgres
File Type Files Lines of Code Total lines
Text 1336 0 472106
C 1325 1069379 1351222
Perl 182 23917 32443
Shell 5 355 533
...

"no block given" errors with cache_money

i've inherited a site that in production is generating dozens of "no block given" exceptions every 5 minutes.
the top of the stack trace is:
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:42:in `add'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:33:in `get'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:22:in `call'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:22:in `fetch'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:31:in `get'
so it appears that the problem is in the cache money plugin.
has anyone experienced something similar?
i've cut and pasted the relevant code below -- anyone more familiar with blocks able to discern any obvious problems?
11 def fetch(keys, options = {}, &block)
12 case keys
13 when Array
14 keys = keys.collect { |key| cache_key(key) }
15 hits = repository.get_multi(keys)
16 if (missed_keys = keys - hits.keys).any?
17 missed_values = block.call(missed_keys)
18 hits.merge!(missed_keys.zip(Array(missed_values)).to_hash)
19 end
20 hits
21 else
22 repository.get(cache_key(keys), options[:raw]) || (block ? block.call : nil)
23 end
24 end
25
26 def get(keys, options = {}, &block)
27 case keys
28 when Array
29 fetch(keys, options, &block)
30 else
31 fetch(keys, options) do
32 if block_given?
33 add(keys, result = yield(keys), options)
34 result
35 end
36 end
37 end
38 end
39
40 def add(key, value, options = {})
41 if repository.add(cache_key(key), value, options[:ttl] || 0, options[:raw]) == "NOT_STORED\r\n"
42 yield
43 end
44 end
line 33 is calling add, but not passing a block, though one is expected on line 42 and there's no block_given? check like there is in the get method. There doesn't really seem to be an appropriate block to pass in this case, as the block passed to get is already yielded to in the add call on line 33, so passing it again separately to add is probably not correct.
Changing line 42 to yield if block_given? should fix your error in this case and shouldn't cause problems elsewhere.
It's also worth noting that line 42 is only called if something was not stored, so you may want to look into why that's happening.

Resources