我很难通过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)
这是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期望,因为代码确实有效(只是测试没有按预期执行!)
答案 0 :(得分:23)
response.should be_success
返回true。但是创建操作重定向,因此响应代码设置为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
答案 1 :(得分:3)
通过测试的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