我正在浏览railstutorial.org上的最新rails指南,我仍然坚持参加某项练习(http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#sec:updating_deleting_exercises上的#8 ).你必须写一个rspec/capybara测试,以确保管理员不能删除自己.我有实施工作,但无法让测试工作正常.这是我的代码.我在这里发现了类似的问题:Ruby on Rails语法和https://getsatisfaction.com/railstutorial/topics/how_to_prevent_admin_user_from_deleting_theself.但我认为这是一个较旧的教程而不是同一个问题.
以下是spec/requests/user_pages_spec.rb中的相关代码:
describe "User pages" do
subject { page }
describe "delete links" do
describe "as an admin user" do
let(:admin) { FactoryGirl.create(:admin) }
before do
sign_in admin
visit users_path
end
it "should not be able to delete themself" do
expect { admin.delete }.should_not change(User, :count)
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
错误消息表示用户数减少了1.
为了完整性,这是我的(工作)实现:
class UsersController < ApplicationController
before_filter :current_admin, only: :destroy
def current_admin
@user = User.find(params[:id])
redirect_to users_path, notice: "Cannot delete …Run Code Online (Sandbox Code Playgroud) 我建立了一个search模型,并且要求至少填写一个字段.我发现了一个有助于验证的问题,Rails:如何要求至少一个字段不为空.(我尝试了所有答案,但Voyta似乎是最好的.)
验证工作正常,除非我想通过attr_accessor或重新定义getter/setter attr_writer.(我在表单上有虚拟属性需要与验证分开.)为了弄清问题是什么,我使用属性作为常规属性进行了测试item_length.如果我添加attr_accessor :item_length,验证将停止工作.所以,我想问题是如何在不使用点表示法的情况下读取属性的值.由于验证使用字符串,我无法使用正常的阅读方式.
这是一个片段:
if %w(keywords
item_length
item_length_feet
item_length_inches).all?{|attr| read_attribute(attr).blank?}
errors.add(:base, "Please fill out at least one field")
end
Run Code Online (Sandbox Code Playgroud)
就像我说的那样,虚拟attrbutes(length_inches和length_feet)根本不起作用,并且普通属性(length)有效,除非我重新定义了getter/setter.