I am having trouble getting one of my rspec/capybara integration specs to pass using the Fabricate gem.
Here is my spec:
it "shows current node as top node on page" do
#node = Fabricate(:node)
visit node_path(#node)
page.should have_content(#node.title)
end
My Fabricator:
Fabricator(:node) do
title { Faker::Lorem.words(3).join(" ") }
description {Faker::Lorem.paragraphs(3).join("\n") }
end
My node's show action:
def show
#node = Node.find(params[:id])
end
My show.html.haml:
%h1= #node.title
The output of my spec:
1) Node shows current node as top node on page
Failure/Error: page.should have_content(#node.title)
expected #has_content?("nostrum qui sed") to return true, got false
And lastly, I put a save_and_open_page, a debug(params) and debug(#node) on the view, here's that output:
action: show
controller: nodes
id: "1"
--- !ruby/object:Node
attributes:
id: "1"
title:
description:
created_at: 2011-06-01 03:14:45.645663
updated_at: 2011-06-01 03:14:45.645663
attributes_cache: {}
changed_attributes: {}
destroyed: false
marked_for_destruction: false
new_record: false
previously_changed: {}
readonly: false
Anybody have any idea why title and description are not being saved to the DB?
Thanks in advance!
----------------- update 6-1 ------------------------
My node model:
class Node < ActiveRecord::Base
attr_accessor :title, :description
validates :title, :presence => true
validates :description, :presence => true
end
In between
#node = Fabricate(:node)
visit node_path(#node)
Try inserting a save! to see if it's a validation issue of some kind:
#node = Fabricate(:node)
#node.save!
visit node_path(#node)
You should probably do a:
class Node < ActiveRecord::Base
attr_accessible :title, :description
validates :title, :presence => true
validates :description, :presence => true
end
Your Model should be
class Node < ActiveRecord::Base
validates :title, :presence => true
validates :description, :presence => true
end
Related
I've some problems with my model tests in ruby. When I try to use a test of validation, the test produces an error. I created a new model (child model) which has the following validations
class Child < ApplicationRecord
has_many :relations, :dependent => :destroy
accepts_nested_attributes_for :relations
belongs_to :user
validates :user, presence: true
validates :name, presence: true, length: { maximum: 50 }
validates :city, presence: true, :on => :create
validates :postalcode, presence: true, numericality: true
validates :streed, presence: true
validates :add_number, presence: true
validates :disability, presence:true, inclusion: { in: [true, false] }
validates :halal, presence:true, inclusion: { in: [true, false] }
validates :koscha, presence:true, inclusion: { in: [true, false] }
validates :vegetarian, presence:true, inclusion: { in: [true, false] }
validates :vegan, presence:true, inclusion: { in: [true, false] }
validates :allday, presence:true, inclusion: { in: [true, false] }
validates :gender, presence: true
I would like to test my model and wanna use as first test the validation of the child:
def setup
#child = Child.new(name: "Example Child", city: "Example City", postalcode: 13, streed: "Example Street",
add_number: 3, disability: true, gender: 1, halal: true, koscha: false,
vegetarian: false, vegan: false, allday:true, user: "hallo")
end
test "should be valid" do
assert #child.valid?
end
and my fixtures for the children look like this:
one:
name: MyString
city: MyString
postalcode: 1
streed: MyString
add_number: 1
disability: false
halal: false
koscha: false
vegetarian: false
vegan: false
allday: false
gender: 1
user_id: 3
I have the problem, that my validation test produces the following error false to be truth and I can't see, what I've done wrong...
I think, it's a very simple fault...
Thank you for your help!
my validation test produces the following error false to be truth and I can't see, what I've done wrong
This means that #child.valid? returns false. Not what assert expects.
I too don't see what you did wrong. Most likely, some validation failing. It's trivial to find out which one. Just inspect #child.errors. Like this, for example.
test "should be valid" do
is_valid = #child.valid? # trigger validation
p #child.errors unless is_valid
assert is_valid
end
I'm betting on this one:
user: "hallo"
This doesn't look like a valid user object.
I'm working through an API for Rails and have been fumbling how to set up the associations, the spec, and the controller for my Get route. The goal - As a user I want to get all the notes closest to my location that have not been viewed. I know the viewed? logic is off, as is the Query Interface in the Recipients Model and Nearests Controller.
Here's the Error Rspec is giving me:
Failure/Error: note1 = create(:note)
NoMethodError:
undefined method `recipient_id=' for #<Note:0x007fd2a40e1400>
Here's the spec:
describe 'GET /v1/notes/nearests?lat=&lon=&radius=' do
it 'returns the notes within the given radius' do
near_note1 = create(:note, lat: 37.760322, lon: -122.429667)
near_note2 = create(:note, lat: 37.760322, lon: -122.429667)
lat = 37.771098
lon = -122.430782
radius = 10
get "/v1/notes/nearests?lat=#{lat}&lon=#{lon}&radius=#{radius}"
expect(response_json).to eq([
{
'id' => [near_note1.id, near.note2.id],
# 'lat' => near_note1.lat,
# 'lon' => near_note1.lon,
'note_text' => [near_note1.note_text, near_note2.note_text],
'photo_uri' => [near_note1.photo_uri, near_note2.photo.uri],
# 'expiration' => near_note.expiration.as_json,
'viewed' => [near_note1.viewed?, near_note2.viewed?]
},
])
end
end
Here is the controller code:
def index
#notes = Note.near([
params[:recipient_id],
params[:lat],
params[:lon]],
radius: :APP_CONFIG['radius'],
units: :APP_CONFIG['units']
)
end
Here are the Factories - Notes
FactoryGirl.define do
factory :note do |u|
sender_id {FactoryGirl.create(:user).id}
recipient_id {FactoryGirl.create(:user).id}
lat 1.5
lon 1.5
note_text "MyString"
photo_uri "MyString"
expiration Time.zone.now.utc
end
end
My Models:
User Model
class User < ActiveRecord::Base
has_many :notes
validates :first_name, :last_name, :pw, presence: true
validates :email, :username, :devicetoken, presence: true, uniqueness: true
validates :email, length: { minimum: 8 }
end
Note Model
class Note < ActiveRecord::Base
belongs_to :user, foreign_key: 'sender_id', class_name: 'User'
has_many :recipients, foreign_key: 'recipient_id', class_name: 'User'
validates :sender_id, presence: true
validates :lat, presence: true
validates :lon, presence: true
validates :note_text, presence:true
validates :expiration, presence: true
reverse_geocoded_by :lat, :lon
end
Recipients Model
class Recipient < ActiveRecord::Base
belongs_to :note, foreign_key: 'recipient_id', class_name: 'Note'
def get_recipient
Note.find(:all, params[:note_id])
end
def viewed?
end
end
I have a record in postgresql of user status it is boolean and its attributes are "true" and "false". I want to show "true" as "active and "false" as "inactive". How do I do it with query or any thing to add in model.
Controller:
def index
#users = User.reorder("id ASC").page(params[:page]).per_page(10)
#count = 0
end
Model:
class User < ActiveRecord::Base
has_many :orders
has_many :order_statuses
attr_accessible :first_name, :last_name, :email, :password,
:password_confirmation, :code
validates :first_name, presence: true
validates :last_name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6}
has_secure_password
before_save { self.email = email.downcase }
before_create :create_remember_token
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
Add this method in your model, and when you call #user.status, it will show 'Active' or "Inactive".
def status
self.status? ? "Active" : "Inactive"
end
Hope, It will help. Thanks
If I understand you correctly you want to display to your users "active" instead of true and "inactive" instead of false.
You could do something like this in all your views:
#user.status? ? 'active' : 'inactive'
Or if you need this in a bunch of places you could write a helper:
module UserHelper
def status_text(user)
#user.status? ? 'active' : 'inactive'
end
end
# and call it from your views like this:
<%= status_text(#user) %>
Or you could put that into a model method if you need this function only in conjunction with the user and it's active method (as per Rails Guy's suggestion)
Lastly you could use I18n to translate the string for you if you have a mulitlingual page:
# en.yml
en:
status:
true: 'active'
false: 'inactive'
# user_helper.rb
def status_text(user)
I18n.t("statys.#{user.status.to_s}")
end
I am a noobie and I am trying to simply get all the records in the database and display them in alphabetical order. Whenever I display the index page the records are always sorted in descending by their id. I used the console to try calling EvalTest.order("name") and again I kept getting the records sorted by their id in descending order instead of by name. Do I need to add an index on the name column to sort by it? This seems like the answer should be so easy but I can't seem to figure it out...
Here is my code:
User Model:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :eval_tests
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
after_validation { self.errors.messages.delete(:password_digest) }
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
Eval_Test Model:
class EvalTest < ActiveRecord::Base
attr_accessible :description, :name
belongs_to :user
validates :user_id, presence: true
validates :name, presence: true
validates :description, presence: true, length: { maximum: 350 }
default_scope order: 'eval_tests.created_at DESC'
end
EvalTest Controller:
class EvalTestsController < ApplicationController
def show
#eval_test = EvalTest.find(params[:id])
end
def new
#eval_test = EvalTest.new
end
def index
#eval_tests = EvalTest.order("name")
end
def create
#eval_test = current_user.eval_tests.build(params[:eval_test])
if #eval_test.save
flash[:success] = "Nouveau test cree!"
redirect_to #eval_test
else
render 'new'
end
end
end
Evaluation Test index.html.erb:
<% provide(:title, 'Index des tests') %>
<h1>Index des tests</h1>
<ul class="eval_tests">
<% #eval_tests.each do |eval_test| %>
<li>
<%= link_to eval_test.name, eval_test %>
</li>
<% end %>
</ul>
This is happening because you have used default scope in your model. Try
#eval_tests = EvalTest.reorder("name")
This should solve your issue.
working when using this in rails c
client = TwitterSearch::Client.new('campvote')
tweets = client.query('#barcampmlk2 #railsforzombies +1')
but not when BarcampSession.update_twitter! it retune empty hash
require 'twitter_search'
class BarcampSession < ActiveRecord::Base
validates :hash_tag , :format => {:with => /^#\w+/ } , :presence => true ,:uniqueness => true
validates :name , :presence => true
validates :email , :presence => true , :format => {:with => /((\S+)#(\S{3}[a-zA-z0-9)]\S*))/ }
validates :handphone, :presence => true
def self.update_twitter!
client = TwitterSearch::Client.new('campvote')
BarcampSession.all.each do |sess|
tweets = client.query('#barcampmlk2 #{sess.hash_tag} +1')
puts tweets.to_yaml
end
end
end
it return
rb(main):014:0> BarcampSession.update_twitter!
--- !seq:TwitterSearch::Tweets []
=> [#<BarcampSession id: 1, hash_tag: "#railsforzombies", name: "wizztjh", email: "wiz123tjh#gmail.com", handphone: "1234006", since: nil, created_at: "2010-12-14 18:28:01", updated_at: "2010-12-14 18:28:01">]
String interpolation works only with double quotes, not single quotes. Change the line
tweets = client.query('#barcampmlk2 #{sess.hash_tag} +1')
to
tweets = client.query("#barcampmlk2 #{sess.hash_tag} +1")