我正在尝试让 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)>'
我曾假设规范没有正确登录用户,但 puts 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
非常感谢...