سؤال

I'm trying to get an RSpec controller spec to pass. It's almost identical to the scaffold-generated spec, except a user is signed into devise first. If I disable 'load_and_authorize_resource' from the controller (which checks permissions), everything works fine. But if I put the line back in, it fails with:

  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)>'

I had assumed the spec wasn't logging in the user correctly, but a puts current_user.role.name confirms the user is logged in correctly, and has the necessary role. Performing the actual process in a browser confirms it works as desired.

Anyone have any suggestions? I'm quite stumped. Controller below:

  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

...And the spec

  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

...And supporting stuff in the spec:

before(:each) do
  @user = Factory(:admin)
  sign_in @user
end

  def mock_post(stubs={})
    @mock_post ||= mock_model(Post, stubs).as_null_object
  end

Many thanks...

هل كانت مفيدة؟

المحلول

Try upgrading CanCan to version 1.5. I had the issue earlier but I think it went away when I upgraded.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top