我在Rails教程的第9章(这次是第9.2.2节)中遇到了(再次!)。我正在
bundle exec rspec spec/
................................FFF........................
Failures:
1) Authentication authorization as wrong user submitting a GET request to the Users#edit action
Failure/Error: before {sign_in user, no_capybara: true}
NoMethodError:
undefined method `new_remember_token' for #<User:0x007f8181815448>
# ./spec/support/utilities.rb:13:in `sign_in'
# ./spec/requests/authentication_pages_spec.rb:71:in `block (4 levels) in <top (required)>'
其他2个错误属于同一类型。
以下是导致错误的规范:
describe "as wrong user" do
let(:user) {FactoryGirl.create(:user)}
let(:wrong_user) {FactoryGirl.create(:user, email: "wrong@example.com")}
before {sign_in user, no_capybara: true}
describe "submitting a GET request to the Users#edit action" do
before {get edit_user_path(wrong_user)}
specify { expect(response.body).not_to match(full_title('Edit user'))}
specify { expect(response).to redirect_to(root_url)}
end
describe "submitting a PATCH request to the Users#update action" do
before { patch user_path(wrong_user)}
specify { expect(response).to redirect_to(root_url)}
end
end
以下是错误消息抱怨的方法(utilities.rb):
def sign_in (user, options={})
if options[:no_capybara]
# Sign in when not using Capybara
remember_token = User.new_remember_token
cookies[:remember_token]
user.update_attribute(:remember_token, User.digest(remember_token))
else
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
end
end
模型的代码(User.rb)在这里:
class User < ActiveRecord::Base
before_save { self.email = email.downcase}
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: {minimum: 6}
has_secure_password
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
我之前遇到过sign_in方法问题,但它miraculously disappeared。我做错了什么?
答案 0 :(得分:0)
我终于找到了我在这种情况下观察到的不稳定测试结果的罪魁祸首,很可能在之前的场合(Failure/Error: sign_in user undefined method `sign_in',Rails named route not recognized)。问题似乎是rails默认情况下不会清除测试之间的缓存。实际上,这是彻头彻尾的可怕。看来你真的不能相信测试结果。我通过评论rails抱怨并重新运行测试的方法来实现这一点。错误持续存在意味着一件事 - rspec只是使用文件的一些缓存版本,因此忽略了我正在做的更改。因此,即使测试通过,您也无法确定它们是否确实如此。这真是奇怪。在通过谷歌搜索实现问题后,我发现如何强制使用rails来清理缓存 - 请查看jaustin的答案:is Rails.cache purged between tests?