Problems with Factory girl and mongoid - ruby

I have this to classes:
class User
...
has_and_belongs_to_many :posts
...
end
class Post
...
has_and_belongs_to_many :users
validates :user_ids, presence: true
...
end
Then I also have this factories:
FactoryGirl.define do
factory :user do
end
end
FactoryGirl.define do
factory :post do
end
end
before I have the validation validates :user_ids, presence: true, it worked well, but when I added that validation, it signals the error in the form so it is good. but rspec doesn't work:
Mongoid::Errors::Validations:
message:
Validation of User failed.
summary:
The following errors were found: Customer ids can't be blank
resolution:
Try persisting the document with valid data or remove the validations.
So I tryed this:
issue on github but for activerecord
blog post
and tried this things:
factory :post do
before_create do |post|
FactoryGirl.build(:user, post: post)
end
end
or
before(:create) do |post|
post.users << FactoryGirl.build(:user, post: post)
end
or
before(:create) do |post|
post.users << FactoryGirl.create(:user, post: post)
end
or
users { create_list(:user, 2) }
or
users { [create(:user, posts: [])] }
but then I get:
bundle exec rspec spec --colour --format documentation
/Users/toni/.rvm/gems/ruby#my-project/bin/ruby_executable_hooks:15: stack level too deep (SystemStackError)

Related

Sinatra Upload multiple files with associated model

i'm trying to make a image gallery with sinatra but a thing that should be simple task is confusing and has a lack of doc and tutorial about it!
So please can someone give a light about this?
for upload i'm using shrine
my biggest doubt is related with name params, should use the galleries model or just images?
class Post < ActiveRecord::Base
validates :title, :content, presence: true, on: :create
has_many :galleries, dependent: :destroy
accepts_nested_attributes_for :galleries, allow_destroy: true
end
require_relative "../uploaders/image_uploader"
class Gallery < ActiveRecord::Base
belongs_to :post
validates :image, presence: true, on: :create
include ImageUploader::Attachment.new(:image)
scope :recent, -> { order('created_at desc') }
# validates_size_of :images, maximum: 2.megabyte, message: "Attachment size exceeds the allowable limit (2 MB)."
end
post controller
post "/posts" do
#post = Post.new(params[:post])
#post.user = current_user
#post.image_derivatives! if #post.image_changed? # creates derivatives
if #post.save
# unless params[:galleries].blank?
# params[:galleries]['image'].each do |a|
# #post.galleries.create!(:image => a)
#end
# end
if params[:post][:galleries][:image] && params[:post][:galleries][:image][:filename]
filename = params[:image][:filename]
file = params[:image][:tempfile]
path = "./public/uploads/#{filename}"
# Write file to disk
File.open(path, "wb") { |f| f.write(file.read) }
end
redirect "/posts/#{#post.slug}"
else
#errors = #post.errors
erb :"/posts/new"
end
end

Rspec for presence validation not working in Rails 5

Model Todo
class Todo < ApplicationRecord
has_many :items, dependent: :destroy
validates :title, :created_by, presence: true
end
RSpecs
require 'rails_helper'
RSpec.describe Todo, type: :model do
it { should have_many(:items).dependent(:destroy) }
it { should validate_presence_of(:title) }
it { should validate_presence_of(:created_by) }
end
When i run the command bundle exec rspec, i see:
Finished in 1.82 seconds (files took 0.97238 seconds to load)
5 examples, 2 failures
Failed examples:
rspec ./spec/models/todo_spec.rb:8 # Todo should validate that :title cannot be empty/falsy
rspec ./spec/models/todo_spec.rb:9 # Todo should validate that :created_by cannot be empty/falsy
Can anyone explain why is it failing?
This is the issue in shoulda-matchers. You need to add to your spec_helper.rb:
RSpec.configure do |config|
config.include(Shoulda::Matchers::ActiveModel, type: :model)
config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

Add a record in Many to many relation fails

I have a many to many connection in Rails applications, it looks like this:
class Workspace
has_and_belongs_to_many :users, dependent: :destroy
end
class User
has_and_belongs_to_many :workspaces
end
class UserWorkspace
belongs_to :user
belongs_to :workspace
end
Schema:
create_table :users_workspaces do |t|
t.integer :user_id
t.integer :workspace_id
t.integer :role, default: 0
t.timestamps null: false
end
Then I want to create a new record like this:
#user.workspaces.create(:workspace_id => #workspace.id, :role => 1)
or this
#user.workspaces << #workspace
and have an error in logs:
(0.0ms) begin transaction
(0.0ms) begin transaction
(0.1ms) rollback transaction
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 207ms (ActiveRecord: 5.5ms)
Completed 500 Internal Server Error in 207ms (ActiveRecord: 5.5ms)
ActiveRecord::UnknownAttributeError (unknown attribute 'workspace_id' for Workspace.):
app/controllers/sessions_controller.rb:10:in `block in sign_up'
app/controllers/sessions_controller.rb:4:in `sign_up'
What am I doing wrong?
PS Controller:
def sign_up
respond_to do |format|
#user = User.new(user_params)
if #user.save
#workspace = Workspace.new(title: "#{#user.name}'s workspace")
#workspace.save
puts "workspace id: #{#workspace.id}"
#user.workspaces.create(:workspace_id => #workspace.id, :role => 1)
puts "workspaces count: #{#user.workspaces.count}"
#user.workspace = #workspace
#user.update_attributes(user_params)
flash.now[:success] = 'Welcome! Please check activation letter in your email box.'
format.js { render 'signup_message' }
else
format.js { render 'render_signup_errors' }
end
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :name, :workspace_id)
end
There are couple of problems with your code. For example, you are creating workspaces that are already created (#user.workspaces.create), or permitting a :workspace_id that is not used, etc.
Pleas see code below:
def sign_up
respond_to do |format|
#user = User.new(user_params)
if #user.save
#workspace = Workspace.new(title: "#{#user.name}'s workspace")
if #workspace.save
# Like this
UserWorkspace.create(user: #user, workspace: #workspace, role: 1)
# Or, like this
#user.user_workspaces.create!(workspace_id: #workspace.id, role: 1)
end
flash.now[:success] = 'Welcome! Please check activation letter in your email box.'
format.js { render 'signup_message' }
else
format.js { render 'render_signup_errors' }
end
end
end
private
# You don't need :workspace_id since you are not using it anywhere
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :name)
end

undefined method `activation_digest=' for #<User:0x007fe3810ceba0> Michael Hartl's book

I am working through Michael Hartl's Rails book and I am about halfway through chapter 10-working on account activation.
I had everything working with the mailers but then when I tried to add a new user, I got the following error message: "undefined method `activation_digest=' for #"
I have been trying to follow along in the book the best that I can. I have my users_controller.rb here:
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update]
before_action :correct_user, only: [:edit, :update]
def new
#user = User.new
end
def index
#users = User.paginate(page: params[:page], :per_page => 10)
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
#user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
else
render 'edit'
end
end
def edit
#user = User.find(params[:id])
end
#confirms if a user is logged in
def logged_in_user
unless logged_in?
store_location
flash[:danger] = "Please Log In."
redirect_to login_url
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
Here is my Model/user.rb:
class User < ActiveRecord::Base
attr_accessor :remember_token, :activation_token
before_save :downcase_email
before_create :create_activation_digest
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
#Returns a random token
def User.new_token
SecureRandom.urlsafe_base64
end
#Remembers a user in the database for use in persistent sessions
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
#Returns true if the given token matches the digest
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
#forgets a user
def forget
update_attribute(:remember_digest, nil)
end
private
# Converts email to all lower-case.
def downcase_email
self.email = email.downcase
end
# Creates and assigns the activation token and digest.
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
The routes I have this:
root 'static_pages#home'
get 'sessions/new'
get 'users/new'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
Please let me know if anything more is needed to be seen. I do have my App up on Github under the name sample_app, my username is ravenusmc.
Looking at your project on Github, your User model doesn't have an activation_token or activation_digest column, nor does the model define them as attributes.
Your User model is trying to write to these columns in the User#create_activation_digest function which is most likely causing the issue.
You'll need to write a migration to add those columns to your User model or add them is attributes (ie attr_accessor) if they are not meant to be persisted.

Fail at redirect expectation in a controller spec

I am using Devise 1.4.2, RSpec 2.6.0 and Rails 3.1.0.rc6. My routes.rb looks like this:
scope "(:locale)", :locale => /e(s|n)/ do
resources :demotivideos, :only => [:index, :show]
devise_for :users
namespace "admin" do
resources :demotivideos, :except => [:index, :show]
end
end
I am spec'ing that, when a not logged in user acces new, create or update, he should be redirected to new_user_session_path. For this, I am using the following code
context "when not logged in" do
before(:each) do
sign_out user
end
describe "GET new" do
it "should redirect to new user session" do
get :new
response.should redirect_to(new_user_session_path)
end
end
describe "POST create" do
it "should redirect to new user session" do
post :create, :demotivideo => valid_attributes
response.should redirect_to(new_user_session_path)
end
end
describe "PUT update" do
it "should redirect to new user session" do
put :update, :id => 1, :demotivideo => valid_attributes
response.should redirect_to(new_user_session_path)
end
end
end
All are failing because of the same reason: expected route includes the locale (by default en) but the actual redirect was to the same path without locale. My application controller was modified as told in Rails Guides:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{ :locale => I18n.locale }
end
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
What am I doing wrong?
Seems like though Rails Guides uses def default_url_options in Devise you need def self.default_url_options. Don't know the difference, though.

Resources