开发者

How to write rspec controller spec model_mock that accounts for no mass assignment

I'm using rspec to test a controller that uses a model that has attr_accessible declared. I don't want to be testing that attr_accesible is working (my model spec does that), but I do want to make sure my controller isn't doing a mass assignment.

Specifically, I have a model like so:

class Post < ActiveRecord::Base
  attr_accessible :body
  validates :body,    :presence => true,
  validates :user,    :presence => true
  belongs_to :user
end

and a slightly tweaked generated controller (xml format lines removed):

  def create
    # this line keeps the rspec test mock happy
    @post = Post.new(params[:post].merge(:user => current_user))

    # Below are the correct lines of code for runtime for attr_accessible
    # @post = Post.new(params[:post])
    # @post.user = current_user            

    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
      else
        format.html { render :action => "new" }
      end
    end
  end

I have a rspec test with a mock controller t开发者_JS百科hat passes with the above:

describe "POST create" do
  describe "with valid params" do
    it "assigns a newly created post as @post" do
      Post.stub(:new).
        with({'body' => 'hi there', 'user' => @user}) { mock_post(:save => true) }
      post :create, :post => {'body' => 'hi there'}
      assigns(:post).should be(mock_post)
    end
  end
end

What I want to do is change the rspec test so that will correctly validate the controller when I comment out the first @post line and uncomment the following two @post lines. That way, I'll be validating that the controller will work work correctly with the real model, but I can continue to use mocks for testing. I've tried several approaches and seem to be going around in circles (and yes, I'm a newbie to Rails and Rspect :p)

Many thanks in advance!


To check against mass assignment. you need to replicate it. so send bad user id in the request

post :create, :post => {'body' => 'hi there', 'user_id' => '2'}

then make sure your created post has the user_id assigned by the controller (assuming its id is not 2 in this example)

assigns(:post)user_id.should be(current_user.id)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜