无法创建对象,验证失败validates_presence_of是触发器

时间:2015-11-10 16:05:00

标签: ruby-on-rails ruby rspec

我有四个模型UserEventParticipantParticipantRole,我正在测试控制器,但我无法为{{event创建current_user 1}}。这些是我的模特

class User < ActiveRecord::Base
  has_many :events
  has_many :participants
  has_many :events, through: :participants
end

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :participants
  has_many :users, through: :participants

  validates_presence_of :user, :name
end

class Participant < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
  belongs_to :participant_role

  validates_presence_of :user, :event, :participant_role
end

class ParticipantRole < ActiveRecord::Base
  has_many :participants
end

当我运行我的测试bundle exec rspec spec/controllers/api/v1/events_controller_spec.rb

RSpec.describe Api::V1::EventsController, type: :controller do

  let(:valid_attributes) { FactoryGirl.attributes_for(:event) }

  let(:valid_session) do
    login_user
  end

  describe 'POST #create' do
    before(:each) do
        request.headers['Authorization'] = valid_session[:token]
        post :create, :event => valid_attributes.merge({ :user_id => valid_session[:id], :event_status_id =>1 }), format: :json
    end

    it 'Should create a new event' do
        is_expected.to respond_with 201
    end
  end
end

我明白了

1) Api::V1::EventsController POST #create Should create a new event
     Failure/Error: post :create, :event => valid_attributes.merge({ :user_id => valid_session[:id], :event_status_id =>1 }), format: :json
     ActiveRecord::RecordInvalid:
       Validation failed: Participant role can't be blank
     # ./app/controllers/api/v1/events_controller.rb:177:in `create'
     # ./app/controllers/concerns/exception_aspects.rb:4:in `exception_wrapper'
     # ./spec/controllers/api/v1/events_controller_spec.rb:23:in `block (3 levels) in <top (required)>' 

在我的EventsController

api :POST, "/events", "Create a new event"
  description "Create a new event"
  param :event, Hash, :required => true, :action_aware => true do
    param :event_status_id, Integer, "id of the status"
    param :name, String, "name of the event"
    param :description, String, "description of the event"
    #param :target_date, DateTime, "date of the event"
    param :avatar, Hash, :required => false do
        param :base64image, String, "Base 64 image file"
    end
    param :is_public, [true, false], "is the event public"
    param :latitude, Numeric, "latitude of the event"
    param :longitude, Numeric, "longitude of the event"
    #param :invite, Array, of: Integer, :desc => "List of friend's id to invite"
 end
formats ['json']
example "URL =>
    :POST, BaseUrl/events
    {event: {
    event_status_id: id of the status,
    name: name of the event,
    description: description of the event,
    target_date: date of the event,
    avatar: photo file,
    is_public: is the event public,
    latitude: latitude of the event,
    longitude: longitude of the event
}}
return =>
{
  {
      \"id\": 1,
      \"user_id\": 1,
      \"event_status_id\": 1,
      \"name\": \"El gran evento\",
      \"description\": \"Blah blah blah blah jiberish blah\",
      \"target_date\": \"2015-11-02T00:00:00.000Z\",
      \"avatar\": {
        \"url\": \"/uploads/event/avatar/1/image20151022-11210-129g2wg.png\",
        \"thumb\": {
          \"url\": \"/uploads/event/avatar/1/thumb_image20151022-11210-129g2wg.png\"
        }
      },
      \"is_public\": true,
      \"latitude\": null,
      \"longitude\": null,
        user:[{
            id: user's id,
            first_name: user' first name,
            last_name: User's last name,
            handle: User's handle}]
    }
}"

error :code => 401, :desc => "Unauthorized"
error :code => 422, :desc => "Unprocessable Entity", :meta => {:errors => "event.errors"}
def create
    default = { "event_status_id" => 1, "user_id" => current_user.id }
    if(params[:event][:avatar])
        if(params[:event][:avatar][:base64image])
            avatar = open_image(params[:event][:avatar][:base64image])
        end
    end
    #avatar = open_image(params[:event][:avatar][:base64image]) if params[:event][:avatar][:base64image]
    friendIds = params[:event][:invite]
    params = default.merge(event_params)
    event = current_user.events.create(params) #Line 177
    #eventParticipant=Participant.new(user_id: current_user.id, event_id: event.id, participant_role_id: Rails.application.config.PARTICIPANT_ROLE_ADMIN)
    #event.avatar = avatar if avatar
    if event.save #&& eventParticipant.save
    #    if(friendIds)
    #        for aux in friendIds
    #            if(Friendship.isFriend(current_user.id,aux))
    #                eventParticipant=Participant.new(user_id: aux, event_id: event.id, participant_role_id: Rails.application.config.PARTICIPANT_ROLE_NON_PAYER)
    #                eventParticipant.save
    #            end
    #        end
    #    end
        event = minify_event(current_user.id, event.id, false)
        render json: event, status: 201
    else
        render json: { errors: event.errors}, status: 422
    end
end

def minify_event(user_id, event_id, getAll)
    if(getAll)
        return Event.joins(:participants).includes(:user).where(participants:{ user_id: user_id}).page(params[:page]).as_json(include:{ user: {only: [:id, :first_name, :last_name, :handle]}},only: [:id, :event_status_id, :name, :description, :target_date, :avatar, :is_public, :latitude, :longitude])
    else
        return Event.joins(:participants).includes(:user).where(participants:{ user_id: user_id}, id: event_id).as_json(include:{ user: {only: [:id, :first_name, :last_name, :handle]}},only: [:id, :event_status_id, :name, :description, :target_date, :avatar, :is_public, :latitude, :longitude]).first
    end
end

def event_params
    #params.require(:event).permit(:event_status_id, :name, :description, :targetDate, :avatar, :isPublic, :latitude, :longitude, :requestIds)
    params.require(:event).permit(:event_status_id, :name, :avatar, :is_public, :latitude, :longitude, :requestIds, :participant_role_id)
end

event = current_user.events.create(params)

当我在rails控制台中使用FactoryGirl创建一个事件对象时,我不会收到错误

event = FactoryGirl.create(:event)

#<Event id: 53, user_id: 2218, event_status_id: 198, name: "Mr. Eryn Metz", description: "Nemo rerum itaque omnis similique qui iusto et fug...", avatar: nil, latitude: #<BigDecimal:7ff269862550,'0.4769934313E2',18(36)>, created_at: "2015-11-10 16:02:23", updated_at: "2015-11-10 16:02:23", target_date: nil, is_public: false, longitude: #<BigDecimal:7ff2698620c8,'-0.770898682E2',18(36)>>

我很感激帮助

1 个答案:

答案 0 :(得分:0)

检查您是否已创建合适的参与者或拥有有效的参与者工厂。错误是:participant_role can't be blank。验证的唯一地方(我们可以看到)是参与者模型。所以我不会看到事件本身的创造。我将关注是否/何时必须创建一个参与者以及该事件失败的原因。希望这有帮助!