А чего вы молчали про rspec_on_rails_matchers? Полезная штука =)
def create
@account = Account.new(params[:account])
@account.save!
redirect_to accounts_url
flash[:notice] = "Account successfully created"
rescue ActiveRecord::RecordInvalid
flash[:error] = "Signup is not successful."
render :action => 'new'
end
А вот тут зачем эксепш перехватывать, просто сделать save почему нельзя?
Вижу много контроллеров, где before_filter :login_required, имхо,
правильнее:
* котроллеры, требующие авторизации положить в /user/
* наследовать их от какого нибудь Base::UserController с
before_filter :login_required
Правильно - before_filter :login_required, или, если вы регулярно
ломаете фильтры в рельсе, - require_login:
class ApplicationController
def self.require_login
before_filter :login_required
end
end
class MyController < ApplicationController
require_login
...
end
(по мотивам acts_as_*)
07.11.2007, в 14:02, Timur Vafin написал(а):
> Правильно - before_filter :login_required, или, если вы регулярно
> ломаете фильтры в рельсе, - require_login:
Почему правильно?
module Spec
module Rails
module Matchers
class HaveAccessible
def initialize(attribute)
@attribute = attribute
end
def matches?(model)
@model = model
initial_value = @model.send @attribute
@model.send "#{@attribute}=", nil
@model.attributes = {@attribute => '1'}
result = @model.attributes_before_type_cast[@attribute] ==
'1'
@model.send "#{@attribute}=", initial_value
result
end
def failure_message
"expected #{@model.class} to have accessible #{@attribute}"
end
def negative_failure_message
"expected #{@model.class} to have protected #{@attribute}"
end
def description
"validate accessibility of #{@attribute}"
end
end
def have_accessible(attribute)
HaveAccessible.new(attribute)
end
end
end
end
и в спеке имеем нечто вроде:
describe Article do
before(:each) do
@article = Article.new
end
%w{title permalink excerpt body comments_allowed}.each do |
attribute|
it "should have accessible #{attribute}" do
@article.should have_accessible(attribute)
end
end
%w{author_id published_at}.each do |attribute|
it "should have protected #{attribute}" do
@article.should_not have_accessible(attribute)
end
end
...
end
Несколько тупая проверка значения в матчере, навереное нужно смотреть
тип column и согласно нему какое-то тестовое значение выставлять, но
для меня работает. Что Вы думаете (тестируете ли вообще такие вещи)?
Кстати идея Universe тоже очень понравилась т.к. решает постоянную
проблему.
Нечто вроде
describe CommentsController do
%w{create edit update destroy}.each do |action|
it "should require authentication on #{action}" do
@controller.should require_authentication_on_action(action)
end
end
end
И
module Spec
module Rails
module Matchers
class RequireAuthenticationOnAction
def initialize(action, response, expected_url)
@action, @response, @expected_url = action, response,
expected_url
end
def matches?(controller)
@controller = controller
return false unless @response.redirect?
@response.redirect_url == @expected_url
end
def failure_message
"expected #{@controller.class} to require authentication on
action #{@action}"
end
def negative_failure_message
"expected #{@controller.class} to allow public access for
action #{@action}"
end
def description
"validate public inaccessibility of #{@action}"
end
end
def require_authentication_on_action(action)
get action
RequireAuthenticationOnAction.new(action, response, login_url)
end
end
end
end
С одной стороны это на тот случай, когда в контроллере есть не только
CRUD actions, а с другой, думаю попытаться в аналогичном ключе
изобразить что-нибудь для ACL, где нагенерить shared behaviours врядли
будет возможно. Или это плохая идея?