[rspec-users] Rspec approach to test model

Scott Taylor scott at railsnewbie.com
Wed Feb 11 11:58:08 EST 2009


On Feb 11, 2009, at 8:51 AM, Kaleem Ullah wrote:

> Hi,
>
> I am quite new to Rspec. I want to use Rspec to test my existing  
> Code. I
> start from Models (Unit Testing). Here i want your help on a issue.
>
> Here is  model/user_spec.rb
>
> describe User do
>  before(:each) do
>    @user=User.new
>    @user.id='2'
>    @user.email='kkkk at gmail.com'
>    @user.password='1234'
>    @user.crypted_password= '21066966a0578362e2115f3561bd4f144520ccd2'
>    @user.salt= '574f09d3ae2473105567eab77ba9d3ae08ed40df'
>    @user.remember_token= ''
>    @user.remember_token_expires_at= ''
>    @user.name= 'kaleem'
>    @user.company_id='2'
>    @user.title= ''
>    @user.active= '1'
>    @user.reset_password_token= ''
>  end

You could benefit from a factory / data builder.  See  
FixtureReplacement, Fixjour, Factory girl, one of the many others out  
there which would build this stuff *once* for you.

>
>
>  it "should authenticate with valid email,password and approved
> company" do
>    User.authenticate(@user.email, @user.password).should_not be_nil
>  end
>
>  it "should NOT authenticate with INvalid email" do
>    @user.email=nil
>    User.authenticate(@user.email, @user.password).should be_nil
>  end
>
>  it "should NOT authenticate with INvalid password" do
>    @user.password=nil
>    User.authenticate(@user.email, @user.password).should be_nil
>  end
>
>  it "should remember me" do
>    @user.remember_me
>    @user.remember_token.should_not be_nil
>    @user.remember_token_expires_at.should_not be_nil
>  end
>
>  it "Remember Token time should be less than Token expires time" do
>    @user.remember_token?.should be_true
>  end
>
>  it "should forget me" do
>    @user.forget_me
>    @user.remember_token.should be_nil
>    @user.remember_token_expires_at.should be_nil
>  end
> end
>
> Now Questions:
> 1) is my approach or way of writing specs is right???

Remember: there is no right way of doing things.  Does it work for you  
(and your team)? Is it clear?

>
> 2) How can i make specs for such a model action
>
>   def activate!
>    self.update_attribute(:active, true)
>   end

spec1:
@user.activate!
@user.should be_active

spec 2:
@user.should_not be_active


Scott


More information about the rspec-users mailing list