[rspec-users] More Rails Pattern Examples?

Pat Maddox pergesu at gmail.com
Mon Nov 12 21:18:17 EST 2007


On Nov 12, 2007 5:38 PM, Vidal Graupera <vgraupera at gmail.com> wrote:
> Hi,
>
> I have been reading the documentation and examples on the rspec site.
> There are two "patterns" from Rails that I am not clear how to
> implement that are kind of related, and so I am not sure how to start.
>
> Does anyone have any examples of how to write rspecs for these?
>
> 1/ Nested resources.
>
> 2/ Resources that are specific to the current_user. In other words, I
> only want to "CRUD" the items that belong to current_user and no
> others. Yes, I am using restful_authentication.
>
> Are there any open source Rails projects that make good use of rspec?
>
> Thanks in advance,
>
> Vidal.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>

# Nested resources
describe MessagesController, " requesting /users/pat/messages using GET" do
  before(:each) do
    @mock_user = mock_model(User, :messages => :pats_messages)
    User.stub!(:find_by_nickname).and_return @mock_user
  end

  def do_get
    get :index, :user_id => "pat"
  end

  it "should find the user" do
    User.should_receive(:find_by_nickname).with("pat").and_return @mock_user
    do_get
  end

  # verified a bit indirectly because the only way to get
  # :pats_messages is by calling @mock_user.messages
  # so the controller would have to be
  # user = User.find_by_nickname params[:user_id]
  # @messages = user.messages
  it "should assign the user's messages to the view" do
    do_get
    assigns[:messages].should == :pats_messages
  end
end

# current user
describe MessagesController, " requesting /messages while logged in" do
  before(:each) do
    @mock_user = mock_model(User, :messages => :user_messages)
    controller.stub!(:current_user).and_return @mock_user
  end

  def do_get
    get :index
  end

  # Same idea as above...the only way to get this result would be with
  # @messages = current_user.messages
  it "should get the logged in user's messages" do
    do_get
    assigns[:messages].should == :user_messages
  end
end



Please keep in mind that I just whipped these up so there may be typos
:)  but you ought to get the idea.  hth

Pat


More information about the rspec-users mailing list