簡體   English   中英

Ruby on Rails控制器測試

[英]Ruby on Rails controller test

我的測試有問題。 我曾使用腳手架來創建我的應用程序,但在控制器中做了一些更改。 我的第一個控制器如下

 class ChildrenController < ApplicationController
   before_action :set_child, only: [:show, :edit, :update, :destroy]

 require 'httparty'
 #  require 'open-uri'
  include HTTParty
  # include I18n


 def child_admin
   @children = Child.all
 end

   # GET /children
   # GET /children.json
   def index
     @children = Child.all

   end

   # GET /children/1
   # GET /children/1.json
   def show
     @child = Child.find(params[:id])
     authorize! :read, @child
   end

  # GET /children/new
   def new
     @child = Child.new
   end

  # GET /children/1/edit
   def edit
   end

   # POST /children
   # POST /children.json
   def create
     @kigas = Kiga.all
     @relations = Relation.all
     @child = Child.new child_params
     @child.user = current_user

     url = "https://maps.googleapis.com/maps/api/geocode/json?address=#{I18n.transliterate(@child.city)}+#{I18n.transliterate(@child.streed)}+#{@child.add_number}&key=AIzaSyBWwoVj5WQMN9-Ij7IJWxQL1CzuigzBsYc"
latlongchild = HTTParty.get(url)
     # puts latlongchild
     # puts latlongchild["results"].first["geometry"]["location"]
     childlat=latlongchild["results"].first["geometry"]["location"]["lat"]
     childlng=latlongchild["results"].first["geometry"]["location"]["lng"]
   #  @child.save
     respond_to do |format|
       if @child.save
         format.html { redirect_to @child, notice: 'Kind wurde erfolgreich registriert.' }
         format.json { render :show, status: :created, location: @child }
       else
         format.html { render :new }
         format.json { render json: @child.errors, status: :unprocessable_entity }
       end
     end
     @kigas.each do |kiga|
       url2 = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{I18n.transliterate(@child.city)}+#{I18n.transliterate(@child.streed)}+#{@child.add_number}&destinations=#{I18n.transliterate(kiga.city)}+#{I18n.transliterate(kiga.streed)}+#{kiga.add_number}&key=AIzaSyDjh9hMXm_lnIyaj_HLQpGvDcDasLjyhxk"
       response = HTTParty.get(url2)
       mesponse=response["rows"].first["elements"].first["distance"]["value"]
            url3 = "https://maps.googleapis.com/maps/api/geocode/json?address=#{I18n.transliterate(kiga.city)}+#{I18n.transliterate(kiga.streed)}+#{kiga.add_number}&key=AIzaSyBWwoVj5WQMN9-Ij7IJWxQL1CzuigzBsYc"
            response2 = HTTParty.get(url3)
            kigalat=response2["results"].first["geometry"]["location"]["lat"]
            kigalng=response2["results"].first["geometry"]["location"]["lng"]
            # puts mesponse
            # puts mysponse
            # puts @child.id
           # puts kiga.id
       @relation = Relation.new relation_params
       @relation.child_id = @child.id
       @relation.kiga_id = kiga.id
       @relation.distance = mesponse
       @relation.kigalat = kigalat
       @relation.kigalong = kigalng
       @relation.childlat = childlat
       @relation.childlong = childlng
       @relation.user_id = @child.user_id
       @relation.save
     end
   end

   # PATCH/PUT /children/1
   # PATCH/PUT /children/1.json
   def update
     respond_to do |format|
       if @child.update(child_params)
         format.html { redirect_to @child, notice: 'Kind wurde erfolgreich angepasst.' }
         format.json { render :show, status: :ok, location: @child }
       else
         format.html { render :edit }
         format.json { render json: @child.errors, status: :unprocessable_entity }
       end
     end
   end

   # DELETE /children/1
   # DELETE /children/1.json
   def destroy
     @child.destroy
     respond_to do |format|
       format.html { redirect_to children_url, notice: 'Kind wurde erfolgreich ausgetragen.' }
  format.json { head :no_content }
     end
   end

   private

     # Use callbacks to share common setup or constraints between actions.
     def set_child
       @child = Child.find(params[:id])
     end

     # Never trust parameters from the scary internet, only allow the white list through.
     def child_params
       params.require(:child).permit(:name, :city, :postalcode, :streed, :add_number, :disability, :halal, :koscha, :vegetarian, :vegan, :allday, :gender)
     end

     def set_relation
       @relation = Relation.find(params[:id])
     end

     # Never trust parameters from the scary internet, only allow the white list through.
     def relation_params
       # params.require(:relation).permit(:kiga_id, :child_id, :assignment, :preference, :distance)
     end
 end

和我的控制器測試如下:

 require 'test_helper'

 class ChildrenControllerTest < ActionDispatch::IntegrationTest
   setup do
     @child = children(:one)
   end

    test "should get index" do
      get children_url
      assert_response :success
    end

   test "should get new" do
     get new_child_url
     assert_response :success
   end

     test "should create child" do
       assert_difference('Child.count') do
         post children_url, params: { child: { add_number: @child.add_number, allday: @child.allday, city: @child.city, disability: @child.disability, gender: @child.gender, halal: @child.halal, koscha: @child.koscha, name: @child.name, postalcode: @child.postalcode, streed: @child.streed, vegan: @child.vegan, vegetarian: @child.vegetarian } }
       end

       assert_redirected_to child_url(Child.last)
     end

    test "should show child" do
      get child_url(@child)
      assert_response :success
    end

   test "should get edit" do
     get edit_child_url(@child)
     assert_response :success
   end

    test "should update child" do
      patch child_url(@child), params: { child: { add_number: @child.add_number, allday: @child.allday, city: @child.city, disability: @child.disability, gender: @child.gender, halal: @child.halal, koscha: @child.koscha, name: @child.name, postalcode: @child.postalcode, streed: @child.streed, vegan: @child.vegan, vegetarian: @child.vegetarian } }
      assert_redirected_to child_url(@child)
         end

   test "should destroy child" do
     assert_difference('Child.count', -1) do
       delete child_url(@child)
     end

     assert_redirected_to children_url
   end
 end

而且我還定義了一些功能:

  class Ability
    include CanCan::Ability

    def initialize(user)

      if user.admin?
        can :manage, :all
        can :view, Child
        can :view, Kiga
        can :read, Kiga
        can :read, Child
        can :read, User

      elsif user.role == 'Eltern'
         can [:update, :destroy], Child do |child|
           child.user_id == user.id
         end
         can :view, Child do |child|
           child.user_id == user.id
         end

         can :read, Child do |child|
           child.user_id == user.id
         end
         can :create, Child

         can :read, Kiga

         can :results_child, Child

         can [:read, :view], Relation do |relation|
           relation.user_id == user.id
           end

     else

   end

   end
 end

我正在使用test_helpercancan的能力。 我以為我的能力變化破壞了我的測試,因為我的indexshowcreateupdate測試通過以下按摩ActionView::Template::Error: undefined method 'admin?' for nil:NilClass產生了錯誤ActionView::Template::Error: undefined method 'admin?' for nil:NilClass ActionView::Template::Error: undefined method 'admin?' for nil:NilClass

有人可以幫我,可以告訴我如何重新安排控制器和測試嗎? 還是還有另一個大錯誤? 非常感謝你!

user.admin? 呼叫是導致錯誤的原因。

所述ability.rb即得到由cancancan產生包括注釋線作為示例的一部分:

# user ||= User.new # guest user (not logged in)

這是因為當您沒有登錄用戶時,會傳入nil來創建Ability實例。

使用user ||= User.new意味着您有一個實際的用戶實例(盡管未保存)可以與之交互。 將這一行作為Abilityinitialize方法中的第一行可能比使所有用戶檢查if user && user.admin?更容易if user && user.admin?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM