I am new to rspec and am finding it all a bit daunting at the moment.
I’d like to be able to adopt a bdd approach to my development but I’m
still at the stage of trying to get my head around rspec concepts so
I’m committing the cardinal sin of coding first and then writing
tests.
I am using the following:
Ruby v1.8.7
Rails v2.3.8
Authlogic v2.1.5
Cancan v1.2.0
rspec v1.3.0
rspec-rails v1.3.2
webrat v0.7.1
cucumber-rails v0.3.2
capybara v0.3.9
factory_girl v1.2.4
pickle v0.3.0
no_peeping_toms v1.1.0
email_spec v0.6.2
In spec_helper.rb, I have
def current_user(stubs = {})
@current_user ||= mock_model(User, stubs)
end
def user_session(stubs = {}, user_stubs = {})
@current_user_session ||= mock_model(UserSession, {:user =>
current_user(user_stubs)}.merge(stubs))
end
def login(session_stubs = {}, user_stubs = {})
UserSession.stub!(:find).and_return(user_session(session_stubs,
user_stubs))
end
def logout
@user_session = nil
end
def login_as_admin
login({}, {:role => ‘admin’})
@current_user.stub(:role?).with(:admin).and_return(true)
end
In ability.rb (for cancan)
def initialize(user)
user ||= User.new # Guest user
if user.role? :admin
can [:index, :show, :new, :edit, :create, :update, :destroy],
[User, CommonContents, Logo]
else
can [:show, :edit, :update], User
cannot [:index, :show, :new, :edit, :create, :update, :destroy],
[CommonContents, Logo]
end
end
In UserController
def create
New users can only be created by admins
authorize! :create, User
When the user is first defined by admin, the password is not set
Create a random one to satisfy validation requirements, which the
user changes when they first visit
params[:user][:password] = random_password()
params[:user][:password_confirmation] = params[:user][:password]
@user = User.new(params[:user])
if @user.save
redirect_to(@user, :notice => ‘User was successfully
created.’)
else
@roles = User.const_get(“ADMIN_CAN_CREATE”)
render :action => “new”
end
end
I have a private method in ApplicationController as follows:
def random_password(length = 10)
alphanumerics = [(‘0’…‘9’),(‘A’…‘Z’),(‘a’…‘z’)].map {|range|
range.to_a}.flatten
(0…length).map
{ alphanumerics[Kernel.rand(alphanumerics.size)] }.join
end
My spec is currently
describe “when authorised as admin” do
describe “POST ‘create’” do
before(:each) do
login_as_admin
end
after(:each) do
logout
end
describe “with valid params” do
it “should set password and password_confirmation to the same 10
digit value” do
# ???
end
end
end
end
I have no idea how to approach 'rspec’ing the creation of the
params[:user][:password] and :password_confirmation or the
random_password method and would very much appreciate it if somebody
could spare the time to suggest what I should be doing.