我正在尝试通过RSpec控制器规范。除了用户首先签署设计之外,它几乎与脚手架生成的规范相同。 如果我从控制器(检查权限)禁用'load_and_authorize_resource',一切正常。但如果我把线重新放入,它将失败:
1) PostsController logged in administrator POST create with valid params assigns a newly created post as @post
Failure/Error: post :create, :post => {'title' => 'test title'}
<Post(id: integer, title: string, cached_slug: string, content: text, user_id: integer, created_at: datetime, updated_at: datetime) (class)> received :new with unexpected arguments
expected: ({"title"=>"test title"})
got: (no args)
# ./spec/controllers/posts_controller_spec.rb:52:in `block (5 levels) in <top (required)>'
我认为规范没有正确登录用户,但是put current_user.role.name确认用户已正确登录,并具有必要的角色。在浏览器中执行实际过程确认它可以按预期工作。
有人有什么建议吗?我很难过。控制器如下:
def create
@post = Post.new(params[:post])
@post.user = current_user
respond_to do |format|
if @post.save
flash[:notice] = "Post successfully created"
format.html { redirect_to(@post)}
format.xml { render :xml => @post, :status => :created, :location => @post }
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
end
end
end
......和规范
describe "with valid params" do
it "assigns a newly created post as @post" do
Post.stub(:new).with({'title' => 'test title'}) { mock_post(:save => true) }
post :create, :post => {'title' => 'test title'}
assigns(:post).should be(mock_post)
end
......并支持规范中的内容:
before(:each) do
@user = Factory(:admin)
sign_in @user
end
def mock_post(stubs={})
@mock_post ||= mock_model(Post, stubs).as_null_object
end
非常感谢......
答案 0 :(得分:1)
尝试将CanCan升级到1.5版。我之前遇到过这个问题,但我认为升级后它就消失了。