1

我正在与 Harlt 的第 9 章练习 9 搏斗。

当我为此练习设计测试时,将 :no_capybara 设置为 true,就像在本教程的其他部分中一样,测试通过,但我收到以下警告:

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)>'

我的两个主要问题是:

  1. 为什么在该测试期间会出现该警告,但在我将 :no_capybara 传递给 sign_in 方法的其他测试中却没有?
  2. 如果我没有通过 no_capybara,为什么我的测试会失败?我在stackoverflow上看到了与这个练习相关的其他问题,其他人的解决方案不需要no_capybara。

以下是我的应用程序中可能适用的所有代码。如果我应该包括更多,请告诉我。

*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
4

1 回答 1

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 正在寻找一种方法,而不仅仅是检查管理员的布尔值。

于 2013-10-12T18:19:41.123 回答