我正在与Harlt的第9章练习9进行搏斗。
当我为此练习设计我的测试时:no_capybara设置为true,就像在本教程的其他部分中一样,测试PASSES,但是我收到以下警告:
WARNING: ignoring the provided expectation message argument (true) since it is not a string.
这个版本的测试在这里:
* spec / requests / authentication_pages_spec.rb *
describe "as an admin user" do
let(:admin) {FactoryGirl.create(:admin)}
before do
sign_in(admin, :no_capybara => true)
end
describe "should not be able to delete itself by direclty submitting request" do
before { delete user_path(admin) }
specify { response.should redirect_to(users_path),
flash[:error].should =~ /Can't delete own admin account/i }
end
end
请注意,这是Hartl在本教程的其他空间中使用该方法的方法,如下所示:
* spec / requests / authentication_pages_spec.rb *
describe 'signed in user' do
let(:user) { FactoryGirl.create(:user) }
before { sign_in user, no_capybara: true }
describe 'unable to access now' do
before {get new_user_path}
specify { expect(response).to redirect_to(root_url)}
end
.
.
.ect...
但是,当我没有设置:no_capybara时,我的测试失败了:
describe "as an admin user" do
let(:admin) {FactoryGirl.create(:admin)}
before { sign_in(admin) }
.
.
.
Failures:
1) Authentication authorization as a non-admin user submitting a DELETE request to the Users#destroy action
Failure/Error: before { delete user_path(user)}
NoMethodError:
undefined method `admin?' for nil:NilClass
# ./app/controllers/users_controller.rb:68:in `admin_user'
# ./spec/requests/authentication_pages_spec.rb:74:in `block (5 levels) in <top (required)>'
我的两个主要问题是:
以下是我的应用中可能适用的所有代码。如果我要加入更多,请告诉我。
* users_controller.rb *
before_action :admin_user, only: :destroy
def destroy
user = User.find(params[:id])
if !current_user?(user)
user.destroy
flash[:success] = "User destroyed. ID: #{user.id}"
else
flash[:error] = "Can't delete own admin account"
end
redirect_to users_path
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
*控制器/助手/ session_helper.rb *
def current_user
remember_token = User.encrypt(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
答案 0 :(得分:0)
我认为在第二种情况下rails无法找到管理员?方法,因为它不存在。 这就是你得到这个错误的原因
NoMethodError:
undefined method `admin?' for nil:NilClass
你是否运行了这些代码
$ rails generate migration add_admin_to_users admin:boolean
$ bundle exec rake db:migrate
$ bundle exec rake test:prepare
根据您的错误,我认为rails正在寻找一种方法,而不仅仅是检查管理员的布尔值。