我很难让 Controller 通过 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
Controller 也是标准配置(直接脱离脚手架)
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 new 的测试
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 期望,因为代码确实有效(只是测试没有按预期执行!)
最佳答案
response.should be_success
如果响应代码在 200-299 范围内,则返回 true。但是创建操作重定向,因此响应代码设置为 302,因此失败。
您可以使用 response.should redirect_to
来测试这一点。 .检查标准 RSpec Controller 生成器的输出作为示例,它可能如下所示:
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
关于ruby-on-rails - 无法使用 rspec Controller POST 创建操作(设计和 cancan)进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4583192/