[英]Cannot test with rspec controller POST create action( devise and cancan)
我很難獲得一個控制器的rspec測試通過。 我想測試POST創建操作是否有效。 我使用rails(3.0.3),cancan(1.4.1),devise(1.1.5),rspec(2.3.0)
這個模型很簡單
class Account < ActiveRecord::Base
attr_accessible :name
end
控制器也是標准配置(直接用於腳手架)
class AccountsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]
load_and_authorize_resource
...
def create
@account = Account.new(params[:account])
respond_to do |format|
if @account.save
format.html { redirect_to(@account, :notice => 'Account was successfully created.') }
format.xml { render :xml => @account, :status => :created, :location => @account }
else
format.html { render :action => "new" }
format.xml { render :xml => @account.errors, :status => :unprocessable_entity }
end
end
end
我想通過的rspec測試是(原諒標題,也許不是最合適的)
it "should call create on account when POST create is called" do
@user = Factory.create(:user)
@user.admin = true
@user.save
sign_in @user #this is an admin
post :create, :account => {"name" => "Jimmy Johnes"}
response.should be_success
sign_out @user
end
然而,我得到的只是
AccountsController get index should call create on account when POST create is called
Failure/Error: response.should be_success
expected success? to return true, got false
# ./spec/controllers/accounts_controller_spec.rb:46
其他行動可以測試並通過(即獲取新的)
這是GET新測試
it "should allow logged in admin to call new on account controller" do
@user = Factory.create(:user)
@user.admin=true
@user.save
sign_in @user #this is an admin
get :new
response.should be_success
sign_out @user
end
完成這里是能力文件
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end
有任何想法嗎? 我的猜測是我使用了錯誤的rspec期望,因為代碼確實有效(只是測試沒有按預期執行!)
如果響應代碼在200-299范圍內,則response.should be_success
返回true。 但是create action重定向,因此響應代碼設置為302,因此失敗。
您可以使用response.should redirect_to
進行測試。 檢查標准RSpec控制器生成器的輸出以獲取示例,如下所示:
it "redirects to the created account" do
Account.stub(:new) { mock_account(:save => true) }
post :create, :account => {}
response.should redirect_to(account_url(mock_account))
end
讓測試通過的rspec測試是(感謝zetetic的建議):
it "should call create on account when POST create is called" do
@user = Factory.create(:user)
@user.admin = true
@user.save
sign_in @user #this is an admin
account = mock_model(Account, :attributes= => true, :save => true)
Account.stub(:new) { account }
post :create, :account => {}
response.should redirect_to(account_path(account))
sign_out @user
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.