Фильтрация result.data и выдача только отфильтрованных элементов в список наблюдения, когда обещание будет выполнено.
function(result) {
$(".dashboardpage .widget-watchlist").render('pages/dashboard/widget-watchlist', {
watchlist: result.data.filter(item => favoriteItemIds.indexOf(item.id) != -1)
}).animo("enterContent");
}
У меня есть очень похожая установка, и ниже код, который я в настоящее время использую для тестирования этого материала. В каждом из describe
с я вставил:
it_should_behave_like "login-required object"
def attempt_access; do_post; end
, Если все Вам нужно, вход в систему, или
it_should_behave_like "ownership-required object"
def login_as_object_owner; login_as @product.user; end
def attempt_access; do_put; end
def successful_ownership_access
response.should redirect_to(product_url(@product))
end
, Если Вам нужно владение. Очевидно, вспомогательные методы изменяются (очень мало) с каждым поворотом, но это делает большую часть работы для Вас. Это находится в моем spec_helper.rb
shared_examples_for "login-required object" do
it "should not be able to access this without logging in" do
attempt_access
response.should_not be_success
respond_to do |format|
format.html { redirect_to(login_url) }
format.xml { response.status_code.should == 401 }
end
end
end
shared_examples_for "ownership-required object" do
it_should_behave_like "login-required object"
it "should not be able to access this without owning it" do
attempt_access
response.should_not be_success
respond_to do |format|
format.html { response.should be_redirect }
format.xml { response.status_code.should == 401 }
end
end
it "should be able to access this if you own it" do
login_as_object_owner
attempt_access
if respond_to?(:successful_ownership_access)
successful_ownership_access
else
response.should be_success
end
end
end
Я нашел несколько ответов на свой собственный вопрос. В основном я должен был понять, как дразнить пользователя от restful_authentication
так, чтобы автоматически сгенерированные rspec тесты контроллера могли передать даже при том, что я добавил before_filter: login_required
.
Вот несколько моих просто найденных ресурсов:
RSpec: Это Должно Вести себя Как
rspec, restful_authentication, и login_required
с помощью restful_authentication current_user в спецификациях контроллера
CRUD Для насмешки зарегистрированного пользователя я взламываю контроллер для установки @current_user
вручную:
module AuthHelper
protected
def login_as(model, id_or_attributes = {})
attributes = id_or_attributes.is_a?(Fixnum) ? {:id => id} : id_or_attributes
@current_user = stub_model(model, attributes)
target = controller rescue template
target.instance_variable_set '@current_user', @current_user
if block_given?
yield
target.instance_variable_set '@current_user', nil
end
return @current_user
end
def login_as_user(id_or_attributes = {}, &block)
login_as(User, id_or_attributes, &block)
end
end
Когда я не тестирую аутентификацию, а тестирую контроллеры, которые требуют аутентификации пользователя, я обычно устанавливаю метод фильтрации:
before(:each) do
controller.stub!(:authenticate).and_return(true)
end
Вышеприведенный пример работает, где мой before_filter установлен на метод аутентификации:
before_filter :authenticate
и аутентификация в моем приложении использует HTTP базовую аутентификацию, но на самом деле это может быть любой другой механизм аутентификации.
private
def authenticate
authenticate_or_request_with_http_basic do |user,password|
user == USER_NAME && password == PASSWORD
end
end
Я думаю, что это довольно простой способ тестирования.