我已更新代码规范代码。
我所寻求的是仅使用创建它的同一用户销毁记录。 我已经在视图部分尝试了它似乎工作,但Rspec给我一些错误。 谁能告诉我如何做正确的规格?
由于
我的记录模型:
class Record < ActiveRecord::Base
#Associations
belongs_to :user
# Validations
validates :user, presence: true
end
我的唱片工厂:
FactoryGirl.define do
factory :record do
user
end
end
我的记录控制器:
class RecordsController < ApplicationController
before_action :find_record, only: [:show, :edit, :update, :destroy]
before_action :require_permission, only: [:destroy]
def destroy
@record.destroy
flash[:notice] = "The record was deleted successfully"
redirect_to @record
end
private
def require_permission
if current_user != Record.find(params[:id]).user
flash[:notice] = "Permission required"
redirect_to root_path
end
end
end
我的记录规范:
require 'rails_helper'
describe RecordsController do
let(:record) { create(:record) }
let(:user) { create(:user) }
describe "#destroy" do
let!(:record) { create(:record) }
#UPDATED
login_user
it "deletes the record" do
expect {
delete :destroy, id: record.id, :record => {:user => record.user}
}.to change(Record, :count).by(-1)
expect(flash[:notice]).to eq("The record was deleted successfully")
end
end
end
更新2
rails_helper.rb
require 'spec_helper'
require 'devise'
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
end
at spec / support / controller_macros.rb
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:admin]
sign_in FactoryGirl.create(:admin) # Using factory girl as an example
end
end
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user)
#user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
end
end
end
我的错误:
#destroy
deletes the record (FAILED - 1)
Failures:
1) RecordsController#destroy deletes the record
Failure/Error: expect {
expected #count to have changed by -1, but was changed by 0
答案 0 :(得分:1)
您使用@record
但是record
这就是为什么错误@record
为零
it "deletes the record" do
expect {
delete :destroy, id: record.id, :record => {:user => record.user}
}.to change(Record, :count).by(-1)
expect(flash[:notice]).to eq("The record was deleted successfully")
end