bug in defining an array in factory gril - ruby-on-rails-4

I using a t.text :emails, array: true, default: [], null:false in my rails 4 migration for emails in the a reporter. There I'm validating each entry with the following code
validates_each :emails do |record, attr, value|
value.each do |email|
record.errors.add attr, I18n.t('reporter.error.not_valid_email', email: email) if (email =~ EMAIL_VALIDATION_REGEXP) == nil
end
end
And I'm getting the following error when I'm creating a instance of the AM class
1) Reporter budget, receipt and member interaction testing the remaining_promise_for_whole_budget_title method for overview of all available budgets
Failure/Error: #reporter = FactoryGirl.create(:reporter)
NoMethodError:
undefined method `each' for "[\"lkajsdf#gmail.com\"]":String
# ./app/models/reporter.rb:6:in `block in <class:Reporter>'
# /Users/malik/.rvm/gems/ruby-2.2.1#maalify/gems/activemodel-4.2.0/lib/active_model/validator.rb:179:in `call'
Here is my factory girl definition
FactoryGirl.define do
factory :reporter do
name "MyReport"
donations %W(1 2)
tanzeems "MyString"
interval "28"
emails ["lkajsdf#gmail.com"]
end
end

FactoryGirl.define do
factory :reporter do
name "MyReport"
donations %W(1 2)
tanzeems "MyString"
interval "28"
emails { ["lkajsdf#gmail.com"] }
end
end
Here's the solution. Let it be in the block.

Related

RSpec: undefined method for #<ActionController::TestResponse. Testing a dynamic flash message

I have a simple spec testing the creation of an object of the Baseline class.
it "allows a user to create a baseline score with valid content" do
expect(#user.baselines.count).to eq(0)
#baseline = post(:create, :user_id => #user.id, :baseline => valid_attributes)
expect(response).to redirect_to '/patients/list'
expect(flash[:notice]).to eq("Baseline scores for case #{#baseline.case_id} was successfully created.")
expect(Baseline.all.count).to eq(1)
end
But I get this. I am uncertain where to begin with this - I am uncertain why I can't access the case_id attribute of #baseline.
NoMethodError:undefined method `case_id' for <ActionController::TestResponse:0x007f8f5ab4f3c0>
Just to show...these are the valid attributes
let(:valid_attributes) do {
:dx1 => "IPF",
:dxcon1 => 100,
:db1 => "Progressive",
:dbcon1 => 100,
:mgt=> "Drugs",
:biopsy => "Yes",
:patient_id => #patient.id,
:case_id => #patient.case,
}
end
post doesn't return a model instance it returns a TestResponse object which gives you access to headers, status code, etc. To access the object created as a side effect of calling the :create action you can do Baseline.last (in this case Baseline.first would also work since there are no existing baseline objects)
Also note - if you have an instance variable named #baseline that is assigned in the controller you can access that with assigns(:baseline)
expect(assigns[:baseline]).to be_a(Baseline)

how to pass 2 data bag variables to template chef

I am trying to pass 2 data bags as variables into a template but it end in error message. Do anyone know how do i pass 2 databags to a template?
Recipe
db = data_bag_item('dbconnect', 'connection')
dbkey = data_bag_item('database', 'databasename')
template '/etc/config.cnf' do
source 'config.cnf.erb'
action :create
variables (
:dbcon => db,
:dbk => dbkey
)
end
Template
connection = mysql://<%= #dbcon['dbuser'] %>:<%= #dbcon['dbpasswd'] %>#<%= #dbcon['dbname'] %>/<%= #dbk['dbname'] %>
Okay. I got the answer.
I missed {} brackets in variables.
db = data_bag_item('dbconnect', 'connection')
dbkey = data_bag_item('database', 'databasename')
template '/etc/config.cnf' do
source 'config.cnf.erb'
action :create
variables ({
:dbcon => db,
:dbk => dbkey
})
end

shoulda validate_inclusion_of not working

Recently upgraded a codebase to rails4 along with gems, now we're getting this error.
Failure/Error: it { is_expected.to ensure_inclusion_of(:usage).in_array(['Index', 'Slide', 'Body']).with_message("%{value} is not a valid usage") }
["Index", "Slide", "Body"] doesn't match array in validation
and here is the related model code
USAGES = ['Index', 'Slide', 'Body']
validates_inclusion_of :usage, :in => USAGES, :message => "%{value} is not a valid usage"
Is there something I'm missing? I don't understand why this is failing.
validate_inclusion_of uses allow_value internally. Admittedly, we should give you a better error message as to what's going on here, but you should be able to write the following tests to figure out what's happening:
it { should allow_value("Index").for(:usage) }
it { should allow_value("Slide").for(:usage) }
it { should allow_value("Body").for(:usage) }
it do
should_not allow_value("something else").
for(:usage).
with_message("%{value} is not a valid usage")
end
My guess is that shoulda-matchers isn't automatically interpolating the %{value} inside of your failure message. If this is true, then what I would do (after filing an issue) is extract the message to an i18n key, and then pass the name of the key to with_message instead.
worked for me -
expect { should validate_inclusion_of(:usage).in?(['a', 'b']) }
should try this -
validates :usage, inclusion: { :in => %w( Index Slide Body ), :message => "%{value} is not a valid usage" }

Rails Fabricator gem with mongoid has_many_and_belongs_to relationship

I'm trying to fabricate a class that has nested elements and has HMABT relationship with another class. Here are my classes
class Quote
has_and_belongs_to_many :providers
belongs_to :user
class Provider
has_and_belongs_to_many :quotes
belongs_to :user
embeds_many :workdones
class Workdone
embedded_in :provider
embeds_many :prices
class Price
embedded_in :workdone
These are my fabricators
Fabricator(:price) do
workdone
variation_id {Fabricate(:variation)._id}
price {12}
discount {5}
end
usern = Faker::Name.last_name
uidn = Faker::Number.number(10)
Fabricator(:user) do
uid 123456
username {usern }
email {Faker::Internet.email}
username_or_uid { [ usern , uidn] }
provider {'facebook'}
name {Faker::Name.name }
gender {'male'}
birthday { Time.at(rand * (18.years.ago.to_f - 50.years.ago.to_f) + 50.years.ago.to_f).to_date }
end
Fabricator(:workdone) do
provider
workdonecount {1}
quotegivencount {1}
rating {5}
active {true}
give_price {true}
end
Fabricator(:provider) do
user
business_address {"Bostanlı Mh., 6352. Sokak No:15, 35480 İzmir, Türkiye"}
business_description {"Biz de sadece epilasyon işleriyle uğraşıyoruz ve bu işlerin
quote(count: 1)
Fabricator(:quote) do
user
providers(count: 3) { Fabricate(:price).workdone.provider }
share_on_facebook_timeline {false}
customer_address {"Bostanlı Mh., 6352. Sokak No:15, 35480 İzmir, Türkiye"}
description {"dasdsadasdsad sadadsssssdsadsasdas"}
location {[27.094637499999976,38.4621336 ] }
variation_id { Fabricate(:variation)._id}
end
When I fabricate quote with Fabricate(:quote)
It gives out this error message
Quote#give_quote works
Failure/Error: Unable to find matching line from backtrace
SystemStackError:
stack level too deep
When I remove quote(count: 1) from provider fabricator it gives out this error.
This works on rails console by the way - providers are created.
Failure/Error: quote = Fabricate(:quote)
TypeError:
no implicit conversion of nil into String
# ./spec/fabricators/quote_fabricator.rb:4:in `block (2 levels) in <top (required)>'
# ./spec/models/quote_spec.rb:51:in `block (3 levels) in <top (required)>'
When I completely remove the providers(count: 3) { Fabricate(:price).workdone.provider }
association from quote fabricator tests pass but of course providers are not created
Does anyone have idea how I can create providers?
Would it be possible to pull three providers from the generated user for this quote? You could do so with the below Fabricator definition.
Fabricator(:quote) do
user
providers { |attrs| attrs[:user].providers.sample(3) }
share_on_facebook_timeline false
customer_address "Bostanlı Mh., 6352. Sokak No:15, 35480 İzmir, Türkiye"
description "dasdsadasdsad sadadsssssdsadsasdas"
location [27.094637499999976,38.4621336]
variation_id { Fabricate(:variation)._id }
end
Also, you only need to use the block syntax if you are dynamically generating values. In the case of all your static values, just passing them in directly (as in the above) will give you a little less overhead.

rspec NoMethodError 'has_content?' 'has_title?'

Im pretty new to ruby on rails.
I just finished this tutorial and i am trying to make my own ruby website from scratch
As soon as i switched my sin-tax to the less verbose one i am getting errors:
the errors I get are:
1) Pages Home page
Failure/Error: it { should have_content('Home') }
NoMethodError:
undefined method `has_content?' for "Home page":String
# ./spec/requests/pages_spec.rb:7:in `block (3 levels) in <top (required)>'
2) Pages Home page
Failure/Error: it { should have_title('Home') }
NoMethodError:
undefined method has_title?' for "Home page":String
# ./spec/requests/pages_spec.rb:8:inblock (3 levels) in '
this is my rspec file
require 'spec_helper'
describe "Pages" do
describe "Home page" do
before { visit root_path }
it { should have_content('Home') }
it { should have_title('Home') }
end
end
I have no idea what is going on did i forget to include something in my gemfile?
If you want any more info comment and ill include it here
Try
it 'has home title' do
expect(page).to have_title('Home')
end
it 'has home content' do
expect(page).to have_content('Home')
end
Or
subject { page }
it { should have_title('Home') }
it { should have_content('Home') }