On 2008-12-05, at 10:06, Daniel Lopes wrote:
Thanks for help and sorry for insistance but I don't understand aspects on rspec ( I think not understand how we use mocks and stubs):

Hi Daniel. If you're a bit unsure about when to use mocks vs stubs, have a read of this article by Martin Fowler:
http://martinfowler.com/articles/mocksArentStubs.html

The short version of that article is:
-You mock objects: @photo = mock_model Photo
-You stub methods: @photo.stub!(:height).and_return(123)

The behavior of my controller is...
Before Filter:
check_administrator_role
load_user

Are you using Authlogic?

So, in this case I want run my before filter methods in before block on rspec, like below:

Nope! =) before-filters are called when a controller action is called; they aren't called in your specs' "before" blocks.

describe PropertiesController do
  def mock_property(stubs={})
    @mock_property ||= mock_model(Property, stubs)
  end

  before do
@current_user = mock_model(User, :id => 1) <== define a current_user with id 1 controller.stub!(:check_administrator_role).and_return(true) <== and current_user is administrator
    @params = {:user_id=>1}  <== define params
User.stub!(:find).with(@params[:user_id]).and_return(@user) <== and now try fetch the user with id 1
  end

Keep in mind that it's
    before :each do
or
    before :all do

  This line will define @user variable, right?
  User.stub!(:find).with(@params[:user_id]).and_return(@user)

That line above tells the User class to return @user when #find is called on it with the argument @params[:user_id] .

You don't need to create a "params" variable. Eg:

before :each do
  @user = mock_model User
  controller.stub!(:check_administrator_role).and_return(true)
  User.stub!(:find).and_return @user
end

But I don't need mock the @user variable to fill it with valid values ( like user_id, name, email and etc ) ?

If you want those methods, you'd stub them on @user, like this:
  @user = mock_model User, :name => 'Bob'
or like this:
  @user = mock_model User
  # ..some other code here..
  @user.stub!(:name).with(no_args).and_return('Bob')

  describe "responding to GET index" do
    it "should expose all properties of given user as @properties" do
      @user.should_receive(:properties).and_return([mock_property])
      get :index
      assigns[:properties].should == [mock_property]
    end
  end

That looks about right.
-Nick
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to