Undefined local variable or method:: ERROR - ruby-on-rails

I'm running 'rake test' and im getting this error
1) Error:
LineItemsControllerTest#test_should_create_line_item:
NameError: undefined local variable or method product for #
test/controllers/line_items_controller_test.rb:21:in block (2 levels) in
test/controllers/line_items_controller_test.rb:20:in block in
The code for line items controller test is
require 'test_helper'
class LineItemsControllerTest < ActionController::TestCase
setup do
#line_item = line_items(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:line_items)
end
test "should get new" do
get :new
assert_response :success
end
test "should create line_item" do
assert_difference('LineItem.count') do
post :create, product_id: products(:ruby).id
end
assert_redirected_to cart_path(assigns(:line_item).cart)
end
test "should show line_item" do
get :show, id: #line_item
assert_response :success
end
test "should get edit" do
get :edit, id: #line_item
assert_response :success
end
test "should update line_item" do
patch :update, id: #line_item, line_item: { cart_id: #line_item.cart_id, product_id: #line_item.product_id }
assert_redirected_to line_item_path(assigns(:line_item))
end
test "should destroy line_item" do
assert_difference('LineItem.count', -1) do
delete :destroy, id: #line_item
end
assert_redirected_to line_items_path
end
end
I don't know if this code from the controller file has something to do with it also. Before this error it was coming up with something about line 3 and not having a local variable or method
def create
product = Product.find(params[:product_id])
#line_item = #cart.add_product(product.id)
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item.cart, notice: 'Line item was successfully created.' }
format.json { render action: 'show', status: :created, location: #line_item }
else
format.html { render action: 'new' }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end

Related

Rails - How to pass controller tests when I use before_action

I need to run some tests and I have come at a stand still here.
I am using before_action in my Appointments controller
Here is the controller
class AppointmentsController < ApplicationController
before_action :set_appointment, only: %i[ show edit update destroy ]
#before we run anything if the user is not signed in show index and show functions
before_action :authenticate_user!, except: [:index,:show]
#only the correct user can edit,update and destroy
before_action :correct_user, only: [:edit, :update , :destroy]
# GET /appointments or /appointments.json
def index
#appointments = Appointment.all.decorate
end
# GET /appointments/1 or /appointments/1.json
def show
end
# GET /appointments/new
def new
##appointment = Appointment.new
#appointment = current_user.appointments.build
end
# GET /appointments/1/edit
def edit
end
#function to allow for search functionality
def search
#appointments = Appointment.where("date LIKE?", "%"+params[:q]+"%")
end
# POST /appointments or /appointments.json
def create
##appointment = Appointment.new(appointment_params)
#appointment = current_user.appointments.build(appointment_params)
#here underneath I am using my custom gem to filter bad words within the notes field when creating an appointment
#appointment.notes = Badwordgem::Base.sanitize(#appointment.notes)
respond_to do |format|
if #appointment.save
format.html { redirect_to appointment_url(#appointment), notice: "Appointment was successfully created." }
format.json { render :show, status: :created, location: #appointment }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /appointments/1 or /appointments/1.json
def update
respond_to do |format|
if #appointment.update(appointment_params)
format.html { redirect_to appointment_url(#appointment), notice: "Appointment was successfully updated." }
format.json { render :show, status: :ok, location: #appointment }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /appointments/1 or /appointments/1.json
def destroy
#appointment.destroy
respond_to do |format|
format.html { redirect_to appointments_url, notice: "Appointment was successfully destroyed." }
format.json { head :no_content }
end
end
#function here that restricts editing so the current logged in user can edit only their records
def correct_user
#appointment = current_user.appointments.find_by(id: params[:id])
redirect_to appointments_path, notice:"NOT ALLOWED TO EDIT THIS" if #appointment.nil?
end
private
# Use callbacks to share common setup or constraints between actions.
def set_appointment
#appointment = Appointment.find(params[:id])
end
# Only allow a list of trusted parameters through.
def appointment_params
params.require(:appointment).permit(:barber, :customer, :notes, :date,:user_id)
end
end
and here is my test controller
require "test_helper"
class AppointmentsControllerTest < ActionDispatch::IntegrationTest
Devise::Test::IntegrationHelpers
setup do
#appointment = appointments(:one)
end
test "should get index" do
get appointments_url
assert_response :success
end
test "should get new" do
get new_appointment_url
assert_response :success
end
test "should create appointment" do
assert_difference('Appointment.count') do
post appointments_url, params: { appointment: { barber: #appointment.barber, customer: #appointment.customer, date: #appointment.date, notes: #appointment.notes } }
end
assert_redirected_to appointment_url(Appointment.last)
end
test "should show appointment" do
get appointment_url(#appointment)
assert_response :success
end
test "should get edit" do
get edit_appointment_url(#appointment)
assert_response :success
end
test "should update appointment" do
patch appointment_url(#appointment), params: { appointment: { barber: #appointment.barber, customer: #appointment.customer, date: #appointment.date, notes: #appointment.notes } }
assert_redirected_to appointment_url(#appointment)
end
test "should destroy appointment" do
assert_difference('Appointment.count', -1) do
delete appointment_url(#appointment)
end
assert_redirected_to appointments_url
end
end
If I comment out the "before actions" in my controller , of course all the tests pass but with them 15 tests fail.
How do I make the tests pass with the before_action ?
For :authenticate_user just use the helper log_in in te test, after create a user, like this:
class AppointmentsControllerTest < ActionDispatch::IntegrationTest
let(:user) { User.new(user_params) }
......
and put
sign_ig user
inside each 'it methods you want'
For :set_appointment or :correct_user just passing right id params inside the path's call

Rails test failure 500 when I use .includes

I'm developing a small e-commerce and I´ve a problem when I run the tests for my cart controller.
here cart controller
class CartsController < ApplicationController
include CurrentCart #modul current_cart in controllers/concerns
before_action :set_cart, only: [:show, :edit, :update, :destroy]
before_action :set_current_cart, only: [:index]
# GET /carts
# GET /carts.json
def index
respond_to do |format|
format.html { redirect_to #cart, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: #line_item }
end
end
# GET /carts/1
# GET /carts/1.json
def show
end
# GET /carts/new
def new
#cart = Cart.new
end
# GET /carts/1/edit
def edit
end
# POST /carts
# POST /carts.json
def create
#cart = Cart.new(cart_params)
respond_to do |format|
if #cart.save
format.html { redirect_to #cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: #cart }
else
format.html { render :new }
format.json { render json: #cart.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /carts/1
# PATCH/PUT /carts/1.json
def update
respond_to do |format|
if #cart.update(cart_params)
format.html { redirect_to #cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: #cart }
else
format.html { render :edit }
format.json { render json: #cart.errors, status: :unprocessable_entity }
end
end
end
# DELETE /carts/1
# DELETE /carts/1.json
def destroy
#cart.destroy if #cart.id == session[:cart_id]
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to catalog_index_url, notice: 'Cart was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cart
#cart = Cart.includes(line_items: :product).find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cart_params
params.fetch(:cart, {})
end
end
and here my tests:
require 'test_helper'
class CartsControllerTest < ActionDispatch::IntegrationTest
setup do
#line_item = line_items(:one)
#product = products(:one)
#cart = carts(:one)
end
test "should get index" do
get carts_url
assert_response :success
end
test "should get new" do
get new_cart_url
assert_response :success
end
test "should create cart" do
assert_difference('Cart.count') do
post carts_url, params: { cart: {} }
end
assert_redirected_to cart_url(Cart.last)
end
test "should show cart" do
get cart_url(#cart)
assert_response :success
end
test "should get edit" do
get edit_cart_url(#cart)
assert_response :success
end
test "should update cart" do
patch cart_url(#cart), params: { cart: {} }
assert_redirected_to cart_url(#cart)
end
test "should destroy cart" do
post line_items_url, params: { product_id: products(:one).id }
#cart = Cart.find(session[:cart_id])
assert_difference('Cart.count', -1) do
delete cart_url(#cart)
end
assert_redirected_to catalog_index_url
end
end
here the results:
Failure: CartsControllerTest#test_should_destroy_cart Expected
response to be a <3XX: redirect>, but was a <500: Internal Server
Error>
Failure: CartsControllerTest#test_should_get_edit Expected response
to be a <2XX: success>, but was a <500: Internal Server Error>
Failure: CartsControllerTest#test_should_update_cart Expected
response to be a <3XX: redirect>, but was a <500: Internal Server
Error>
here is the modul current cart for the cartsController:
module CurrentCart
private
def set_current_cart
#cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
#cart = Cart.create
session[:cart_id] = #cart.id
end
end
I think that the problem is here:
if I remove this in the method set_cart from the cart controller: .includes(line_items: :product) the tests will run perfectly without failure, but I cannot understand why.
(I put the include because otherwise I get this error when I access the cart from the browser:
USE eager loading detected LineItem => [:product] Add to your
finder: :includes => [:product] Call stack
UPDATE:
I found something interesting in the file "test.log" :
Bullet::Notification::UnoptimizedQueryError - user: claudio
DELETE /carts/980190963
AVOID eager loading detected
LineItem => [:product]
Remove from your finder: :includes => [:product]
Call stack
##here there's a path##.rb:45:in `block (2 levels) in <class:CartsControllerTest>'
##here there's a path##:in `block in <class:CartsControllerTest>'

RSpec undefined method `request='

I am getting the following error from a RSpec get request:
1) Flight GET/index displays flights
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `request=' for #<Flight:0x00000006a2ad68>
Here is my spec/requests/flights_spec.rb :
require 'rails_helper'
require 'spec_helper'
require 'flight'
RSpec.describe Flight, type: :controller do
describe 'GET/index', :type => :request do
it 'displays flights' do
Flight.create!(:destination => 'San Francisco')
get :index
response.body.should include('San Francisco')
end
end
end
Here is my spec/controllers/flights_controller_spec.rb:
require 'rails_helper'
RSpec.describe FlightsController, type: :controller do
describe 'GET index' do
end
end
Here is my app/controllers/flights_controller.rb:
class FlightsController < ApplicationController
before_action :set_flight, only: [:show, :edit, :update, :destroy]
# GET /flights
# GET /flights.json
def index
#flights = Flight.all
end
# GET /flights/1
# GET /flights/1.json
def show
end
# GET /flights/new
def new
#flight = Flight.new
end
# GET /flights/1/edit
def edit
end
# POST /flights
# POST /flights.json
def create
#flight = Flight.new(flight_params)
respond_to do |format|
if #flight.save
format.html { redirect_to #flight, notice: 'Flight was successfully created.' }
format.json { render :show, status: :created, location: #flight }
else
format.html { render :new }
format.json { render json: #flight.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /flights/1
# PATCH/PUT /flights/1.json
def update
respond_to do |format|
if #flight.update(flight_params)
format.html { redirect_to #flight, notice: 'Flight was successfully updated.' }
format.json { render :show, status: :ok, location: #flight }
else
format.html { render :edit }
format.json { render json: #flight.errors, status: :unprocessable_entity }
end
end
end
# DELETE /flights/1
# DELETE /flights/1.json
def destroy
#flight.destroy
respond_to do |format|
format.html { redirect_to flights_url, notice: 'Flight was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_flight
#flight = Flight.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def flight_params
params.require(:flight).permit(:departure, :arrival, :destination, :baggage_allowance, :capacity)
end
end
Not sure what's gong on - any help appreciated - thanks in advance,
Slavko
At the top of your spec you've got
RSpec.describe Flight, type: :controller
But then just below
describe "GET /index", type: :request
You've got to pick one or the other (from what's in the spec you probably want a controller spec)
In addition for a controller spec the described object should be a controller class, not a model class.

Rails Controllers tests are not working

I am trying to do my first tests on rails but I am having troubles with it.
I am trying just to test one controller to understand how it works but it doesn't work.
I added the Devise helper to avoid problems with it but I still getting many errors.
I really appreciate so much any kind of help.
Here is the code of the Test Controller:
reportes_controller_test.rb
require 'test_helper'
class ReportesControllerTest < ActionController::TestCase
include Devise::TestHelpers
setup do
#reporte = reportes(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:reportes)
end
test "should get new" do
get :new
assert_response :success
end
test "should create report" do
assert_difference('Reporte.count') do
post :create, reporte: { asignacion_actividad_id: #reporte.asignacion_actividad_id, descripcion: #reporte.descripcion}
end
assert_redirected_to reporte_path(assigns(:reporte))
end
test "should show report" do
get :show, id: #reporte
assert_response :success
end
test "should get edit" do
get :edit, id: #reporte
assert_response :success
end
test "should update report" do
patch :update, id: #reporte, reporte: { asignacion_actividad_id: #reporte.asignacion_actividad_id, descripcion: #reporte.descripcion}
assert_redirected_to reporte_path(assigns(:reporte))
end
test "should destroy report" do
assert_difference('Reporte.count', -1) do
delete :destroy, id: #reporte
end
assert_redirected_to reportes_path
end
end
Here is the code of the Controller:
reportes_controller.rb
class ReportesController < ApplicationController
before_action :set_reporte, only: [:show, :edit, :update, :destroy]
# asd
#
# GET /reportes
# GET /reportes.json
def index
authorize! :index, Reporte
#asignacion_actividades = AsignacionActividad.find_by(actividad_id: params[:actividad_id])
#actividad = #asignacion_actividades.actividad
#proyecto = #actividad.proyecto
#reportes_mios = []
#asignacion_actividades.to_a.each do |asignacion|
if asignacion.usuario == current_usuario && !asignacion.reportes.nil?
#reportes_mios = #reportes_mios + asignacion.reportes
end
end
#reportes_todos = #actividad.reportes
#reportes_todos = [] if #reportes_todos.nil?
#reportes_mios = [] if #reportes_mios.nil?
#reportes_todos = #reportes_todos.uniq
#reportes_mios = #reportes_mios.uniq
end
# GET /reportes/1
# GET /reportes/1.json
def show
authorize! :show, Reporte
end
# GET /reportes/new
def new
authorize! :new, Reporte
#actividad = Actividad.find(params[:actividad_id])
#proyecto = #actividad.proyecto
#asignacion_actividad = #actividad.asignacion_actividades.where('vigente =? and usuario_id =?', 'true' , current_usuario.id).uniq.last
#asignacion_actividad_id = #asignacion_actividad.id
#reporte = Reporte.new
end
# GET /reportes/1/edit
def edit
authorize! :edit, Reporte
end
# POST /reportes
# POST /reportes.json
def create
authorize! :create, Reporte
#reporte = Reporte.new(reporte_params)
respond_to do |format|
if #reporte.save
format.html { redirect_to :action => 'index', :actividad_id => #reporte.asignacion_actividad.actividad.id
flash[:notice] = 'Reporte was successfully created.' }
format.json { render :show, status: :created, location: #reporte }
else
format.html { render :new }
format.json { render json: #reporte.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /reportes/1
# PATCH/PUT /reportes/1.json
def update
authorize! :update, Reporte
respond_to do |format|
if #reporte.update(reporte_params)
format.html { redirect_to #reporte, notice: 'Reporte was successfully updated.' }
format.json { render :show, status: :ok, location: #reporte }
else
format.html { render :edit }
format.json { render json: #reporte.errors, status: :unprocessable_entity }
end
end
end
# DELETE /reportes/1
# DELETE /reportes/1.json
def destroy
authorize! :destroy, Reporte
#reporte.destroy
respond_to do |format|
format.html { redirect_to reportes_url, notice: 'Reporte was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_reporte
#reporte = Reporte.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def reporte_params
params.require(:reporte).permit(:descripcion, :asignacion_actividad_id)
end
end
And here is the error that I get when i try to execute it:
rake test TEST=test/controllers/reportes_controller_test.rb
Run options: --seed 7969
# Running:
FFFFFFE
Finished in 0.540113s, 12.9603 runs/s, 11.1088 assertions/s.
1) Failure:
ReportesControllerTest#test_should_create_report [/home/blackswan/proyectoFinal/SEVU/test/controllers/reportes_controller_test.rb:21]:
"Reporte.count" didn't change by 1.
Expected: 3
Actual: 2
2) Failure:
ReportesControllerTest#test_should_destroy_report [/home/blackswan/proyectoFinal/SEVU/test/controllers/reportes_controller_test.rb:44]:
"Reporte.count" didn't change by -1.
Expected: 1
Actual: 2
3) Failure:
ReportesControllerTest#test_should_get_edit [/home/blackswan/proyectoFinal/SEVU/test/controllers/reportes_controller_test.rb:35]:
Expected response to be a <success>, but was <302>
4) Failure:
ReportesControllerTest#test_should_get_index [/home/blackswan/proyectoFinal/SEVU/test/controllers/reportes_controller_test.rb:11]:
Expected response to be a <success>, but was <302>
5) Failure:
ReportesControllerTest#test_should_get_new [/home/blackswan/proyectoFinal/SEVU/test/controllers/reportes_controller_test.rb:17]:
Expected response to be a <success>, but was <302>
6) Failure:
ReportesControllerTest#test_should_show_report [/home/blackswan/proyectoFinal/SEVU/test/controllers/reportes_controller_test.rb:30]:
Expected response to be a <success>, but was <302>
7) Error:
ReportesControllerTest#test_should_update_report:
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"reportes", :id=>nil} missing required keys: [:id]
test/controllers/reportes_controller_test.rb:40:in `block in <class:ReportesControllerTest>'
7 runs, 6 assertions, 6 failures, 1 errors, 0 skips
What can i do? If i solve this error I will be able to test all the controllers.
I will appreaciate any answer. Thank you for your time.
I think it about authorization, is your controller works well?
If you don't mind, you can take a look on RedMine, it has many test case to refer.

Rspec - controller test error - Paperclip::AdapterRegistry::NoHandlerError: No handler found for "#<File:0x531beb0>"

I asked about my Rspec test as follow.
Rspec - RuntimeError: Called id for nil, which would mistakenly be 4
On the same code (Rspec test for "items_controller.rb"), I am trying to make the test for "PUT update". However I got the error "Paperclip::AdapterRegistry::NoHandlerError: No handler found for "#".
My Rspec test is as follow. Honestly, I guess that the cause of this fail is ""photo" => File.new(Rails.root + 'app/assets/images/rails.png')" on "let(:valid_attributes)". However, I tried several ways but I couldn't fix.
By the way, my rails version is "Rails 3.2.14". Then I tried following post, but also couldn't.
Can't figure out what's causing my tests to fail
The error is as follows.
......F....
Failures:
1) ItemsController PUT update could not update successfully
Failure/Error: put :update, {:id => item.to_param, :item => valid_attributes}, valid_session
Paperclip::AdapterRegistry::NoHandlerError:
No handler found for "#<File:0x5d4c548>"
# ./app/controllers/items_controller.rb:110:in `block in update'
# ./app/controllers/items_controller.rb:108:in `update'
# ./spec/controllers/items_controller_spec.rb:95:in `block (3 levels) in <top (required)>'
Finished in 1.75 seconds
11 examples, 1 failure
Failed examples:
rspec ./spec/controllers/items_controller_spec.rb:91 # ItemsController PUT update could not update successfully
Randomized with seed 40912
My Rspec test is as follows.
require 'spec_helper'
require 'date'
describe ItemsController do
let(:valid_attributes) { {
"days" => "1",
"hours" => "1",
"minutes" => "1",
"name"=>"HogeHoge" ,
"category" => "Gift",
"min_bid_price" => "100.0",
"description" => "HogeHoge",
"photo" => File.new(Rails.root + 'app/assets/images/rails.png')
} }
let(:valid_session) { {} }
it "returns http success" do
get "index"
response.should be_success
end
it "returns http success" do
get "new"
response.should be_success
end
describe "POST create" do
it "" do
#declare the objects and stubs
current_user = User.new(id:'1')
current_user.save
#"current_user=(user)" function on controller
controller.current_user = current_user
#auction
auction = Auction.new(id:'1',highest_bid_id:'1', extend_bit:'1')
auction.save
Auction.stub(:find_by_id).and_return(auction)
#bid
bid = Bid.new(auction_id:'1',amount:'150.0')
bid.save
Bid.stub(:find_by_id).and_return(bid)
#item
item = Item.new(id:'1',auction_id:'1',min_bid_price:'100.0')
item.save
Item.stub(:find_by_id).and_return(item)
date = DateTime.now
post :create, {:item => {'id' => '2','days'=>'1','hours'=>'1','minutes'=>'1','created_at'=>date}}
response.should be_success
end
end
describe "GET index" do
it "assigns all items as #items" do
item = Item.create! valid_attributes
get :index, {}, valid_session
assigns(:items).should eq([item])
end
end
describe "GET show" do
it "assigns the requested item as #item" do
item = Item.create! valid_attributes
get :show, {:id => item.to_param}, valid_session
assigns(:item).should eq(item)
end
end
describe "GET new" do
it "assigns a new item as #item" do
get :new, {}, valid_session
assigns(:item).should be_a_new(Item)
end
end
describe "GET edit" do
it "assigns the requested item as #item" do
item = Item.create! valid_attributes
get :edit, {:id => item.to_param}, valid_session
assigns(:item).should eq(item)
end
end
describe "PUT update" do
it "could not update successfully" do
item = Item.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Item.any_instance.stub(:save).and_return(false)
put :update, {:id => item.to_param, :item => valid_attributes}, valid_session
assigns(:item).should eq(item)
response.should redirect_to(#item)
end
it "could not update successfully" do
item = Item.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Item.any_instance.stub(:save).and_return(false)
put :update, {:id => item.to_param, :item => { }}, valid_session
response.should render_template("edit")
end
end
describe "DELETE destroy" do
it "destroys the requested item" do
item = Item.create! valid_attributes
expect {
delete :destroy, {:id => item.to_param}, valid_session
}.to change(Item, :count).by(-1)
end
it "redirects to the items list" do
item = Item.create! valid_attributes
delete :destroy, {:id => item.to_param}, valid_session
response.should redirect_to(items_url)
end
end
end
My "items_controller.rb" is as follw.
require 'timers'
class ItemsController < ApplicationController
#instance of current user
def current_user=(user)
#current_user ||= user
end
def extendtimer
Auction.find_by_id(#auction_id).update_attributes(:extend_bit => 0)
#exp = Auction.find_by_id(#auction_id).exp_time + 2.minutes
Auction.find_by_id(#auction_id).update_attributes(:exp_time => #exp)
#min = Item.find_by_id(#item_id).minutes + 2
Item.find_by_id(#item_id).update_attributes(:minutes => #min)
#timer2 = Timers.new
#extend_timer = #timer2.after(120){ buy }
#timer2.wait
end
def buy
if Auction.find_by_id(#auction_id).extend_bit == 1
extendtimer
else
if Auction.find_by_id(#auction_id).highest_bid_id != 0
Item.find_by_auction_id(#auction_id).update_attributes(:sold => 1, :sold_to => Bid.find_by_id(Auction.find_by_id(#auction_id).highest_bid_id).user_id )
MyMailer.auction_winner_email(Auction.find_by_id(#auction_id)).deliver
else
Item.find_by_auction_id(#auction_id).update_attributes(:sold => 0, :sold_to => 0 )
MyMailer.no_bids_email(Auction.find_by_id(#auction_id)).deliver
end
#t1.join
end
end
def index
#items = Item.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #items }
end
end
# GET /items/1
# GET /items/1.json
def show
#item = Item.find(params[:id])
respond_to do |format|
#format.html # show.html.erb
format.html { render layout: (request.headers["X-Requested-With"] != 'XMLHttpRequest') }
format.json { render json: #item }
end
end
# GET /items/new
# GET /items/new.json
def new
#item = Item.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #item }
end
end
# GET /items/1/edit
def edit
#item = Item.find(params[:id])
end
# POST /items
# POST /items.json
def create
#item = Item.new(params[:item])
#item.user_id = current_user.id
respond_to do |format|
if #item.save
format.html { redirect_to #item, notice: 'Item was successfully created.' }
format.json { render json: #item, status: :created, location: #item }
else
format.html { render action: "new" }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
#elapsed_seconds =(((params[:item][:days].to_i * 24)+params[:item][:hours].to_i)*60+params[:item][:minutes].to_i)*60
#auction = Auction.create(:item_id => #item.id, :highest_bid_id => 0, :exp_time => #item.created_at+ #elapsed_seconds.seconds, :suspend => 0, :user_id => #current_user.id, :extend_bit => 0 )
#item.update_attributes(:auction_id => #auction.id)
#item_id = #item.id
#auction_id = #auction.id
#t1 = Thread.new{
#timer = Timers.new
#bid_timer = #timer.after(#elapsed_seconds){
if Auction.find_by_id(#auction_id).suspend != 1
buy
end
}
#timer.wait
}
end
# PUT /items/1
# PUT /items/1.json
def update
#item = Item.find(params[:id])
respond_to do |format|
if #item.update_attributes(params[:item])
format.html { redirect_to #item, notice: 'Item was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /items/1
# DELETE /items/1.json
def destroy
#item = Item.find(params[:id])
#item.destroy
respond_to do |format|
format.html { redirect_to items_url }
format.json { head :no_content }
end
end
end
I would like to have someone's advice. Thank you in advance.
Try using Rack::Test::UploadedFile instead of File.new
require 'rack/test'
Rack::Test::UploadedFile.new('fixtures/test_file.png', 'image/png')
im pretty sure your problem is with the form_for in the view,
try something like this:
<%= form_for #restaurante, :html => { :multipart => true } do |form| %>
Nome:<%= form.text_field :nome%>
Endereço:<%= form.text_field :endereco %>
Especialidade:<%= form.text_field :especialidade %>
Foto:<%= form.file_field :foto %>
<%= form.submit 'create'%>
<% end %>
Make sure it's multipart/form-data in the test.
I have a helper method for this.
module Support
module Acceptance
module ClassMethods
def multipart_form_data!
header 'Accept', 'application/json'
header 'Content-Type', 'multipart/form-data'
end
end
end
end

Resources