在rspec请求测试期间,current_user没有获取值?

时间:2017-09-23 08:10:02

标签: ruby-on-rails ruby api testing rspec

我想在rspec测试中获取current_user值,但我没有得到我正在创建当前用户,在byebug中我可以看到current_user,我也可以在admin表中看到admin_user但是我收到错误管理员用户不可用。

故障:

1)营地API帖子/阵营在请求有效时创建一个阵营      失败/错误:@camp = current_user.camps.create!(camp_params)

 ActiveRecord::InvalidForeignKey:
   PG::ForeignKeyViolation: ERROR:  insert or update on table "camps" violates foreign key constraint "fk_rails_25370d4fd7"
   DETAIL:  Key (admin_id)=(27) is not present in table "admins".
   : INSERT INTO "camps" ("name", "fees", "course", "website", "created_at", "updated_at", "admin_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"

现在看到再见错误

Admin id: 27, email: "cordelia@king.biz", created_at: "2017-09-23 07:50:32", updated_at: "2017-09-23 07:50:32", authentication_token: "id2a9_K4LfRHJzo6bTNy", first_name: "jamalalll", last_name: "saleemsxd">

现在检查创建current_user

的代码
def bypass_authentication
  current_user = FactoryGirl.create(:admin)`

  ApplicationController.send(:alias_method, :current_user,:current_user)
  ApplicationController.send(:define_method, :current_user) do
    current_user
  end
  current_user
end

def restore_authentication
  ApplicationController.send(:alias_method, :current_user, :old_current_user)
end

现在我正在为我的api执行请求测试

require 'rails_helper'
require 'authentication_helper'

RSpec.describe 'Camp API' , type: :request do
 #initialize the factory
  let!(:camps) {create_list(:camp, 1)}
  let!(:ratings){create_list(:rating, 1)}

  let(:camp_id) {camps.first.id}
  before {bypass_authentication}

  # test  for the GET /camps
  describe 'GET /camps' do

    #make http GET request before  '/camps'
    before {get '/camps'}
    it 'return camps' do
      expect(json).not_to be_empty
      expect(json.size).to eq(1)
    end

    it "returns status code 200" do
      expect(response).to have_http_status (200)
    end
  end

  # test for the GET  /camps/:id
  describe 'GET /camps/:id' do
    before {get "/camps/#{camp_id}"}

    context 'when the record exist' do
        it 'returns to camp' do
            expect(json).not_to be_empty
            expect(json[0]['id']).to eq(camp_id)
      end

      it 'returns status code 200' do
        byebug
        expect(response).to have_http_status(200)
      end
    end
  end

  # test of Post /campa
  describe 'Post /camps' do
    let(:validate_attributes){ {name: "exponent", fees: "300" , course: "Web Development", website: "www.example.com"}}

    context "when the request is valid" do
        before { post '/camps', params: validate_attributes}

        it "create a camp" do
        expect(json['name']).equal?('exponent')

        end

        it "returns the status code 201" do
        expect(response).to have_http_status(201)
        end
    end

    context "when request is not valid" do
      before{ post '/camps', params: {name: 'not camp'}}

      it "return status code 422" do
        expect(response).to  have_http_status(422)
      end

      it "return the validation failure message" do
        expect(response.body).to match(/Validation failed: Fees can't be blank, Website can't be blank, Course can't be blank/)
      end
    end
  end

  # test for put camps/:id
  describe 'PUT /camps/:id' do
    let(:validate_attributes){{nane: 'not camp'}}

    context "when the record exist" do
      before {put "/camps/#{camp_id}", params: validate_attributes}

      it "updates the record" do
        expect(response.body).to be_empty
      end

      it "returns the code 204" do
        expect(response).to  have_http_status(204)

      end
    end
  end

  # test for delete /camp:id
  describe  'DELETE /camps/:id' do
    before {delete "/camps/#{camp_id}"}

    it "returns the code status 204" do
        expect(response).to have_http_status(204)
    end
  end
end

1 个答案:

答案 0 :(得分:0)

这是我面临的实际问题

 Admin id: 27, email: "cordelia@king.biz", created_at: "2017-09-23 07:50:32", updated_at: "2017-09-23 07:50:32", authentication_token: "id2a9_K4LfRHJzo6bTNy", first_name: "jamalalll", last_name: "saleemsxd">

我找到了解决方案,经过30个小时的工作并应用了不同的解决方案。

基本上,我使用单表继承并为子模型提供外键约束。我们不能使用child一个外键约束。我们需要使用parent一个外键约束。

class AdminUser < User
  has_many :camps, foreign_key: "user_id" 
end

这里的admin用户是从User继承的,我想创建一个与adminusers和camps表之间的关系。但它驻留表的外键将是user_id而不是admin_id,架构将如下所示

create_table "camps", force: :cascade do |t|
    t.string "name"
    t.integer "fees"
    t.string "course"
    t.integer "graduation_rate"
    t.integer "employment_rate"
    t.integer "averge_salary"
    t.string "website"
    t.string "facebook"
    t.string "twitter"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.index ["user_id"], name: "index_camps_on_user_id"
  end