0

我正在尝试测试登录时应该/不应该看到的链接,但 RSpec 抛出以下错误:

Failure/Error: before { sign_in user }
ThreadError:
  Attempt to unlock a mutex which is not locked
  # (eval):2:in `click_button'
  # ./spec/support/utilities.rb:5:in `sign_in'
  # ./spec/views/header_spec.rb:19:in `block (3 levels) in <top (required)>'

我的测试块看起来像这样:

describe "when signed in" do
  let(:user) { FactoryGirl.create(:user) }
  before { sign_in user }

  it { should have_link("Sign out") }
  it { should_not have_link("Sign up") }
  it { should_not have_link("Log in") }
end 

还有我的登录功能:

def sign_in(user)
  click_link "Log in"
  fill_in "username", with: user.username
  fill_in "password", with: user.password
  click_button "Log me in!"
  cookies[:remember_token] = user.remember_token
end

我试着换了

click_button "Log me in!"

find(:button, "Log me in!").click

并导致以下错误:

Nokogiri::CSS::SyntaxError:
   unexpected '!' after '[#<Nokogiri::CSS::Node:0x00000003645778 @type=:DESCENDANT_SELECTOR, @value=[#<Nokogiri::CSS::Node:0x000000036464e8 @type=:ELEMENT_NAME, @value=["Log"]>, #<Nokogiri::CSS::Node:0x000000036458b8 @type=:DESCENDANT_SELECTOR, @value=[#<Nokogiri::CSS::Node:0x00000003645f98 @type=:ELEMENT_NAME, @value=["me"]>, #<Nokogiri::CSS::Node:0x000000036459f8 @type=:ELEMENT_NAME, @value=["in"]>]>]>]'
 # (eval):3:in `_racc_do_parse_c'
 # (eval):3:in `do_parse'
 # (eval):2:in `find'
 # ./spec/support/utilities.rb:5:in `sign_in'
 # ./spec/views/header_spec.rb:19:in `block (3 levels) in <top (required)>'

然后我尝试用“登录”替换我的按钮文本,不带感叹号,Capybara 抛出 ElementNotFound 错误:

Failure/Error: before { sign_in user }
 Capybara::ElementNotFound:
   Unable to find css "Log me in"
 # (eval):2:in `find'
 # ./spec/support/utilities.rb:5:in `sign_in'
 # ./spec/views/header_spec.rb:19:in `block (3 levels) in <top (required)>'

总的来说,我对 RSpec 和 Rails 还是很陌生,但到目前为止,我已经能够很好地找到自己的方式。这个让我完全难住了。

4

1 回答 1

1

所以昨晚胡思乱想之后,我终于找到了解决方案,并迅速开始面对桌面。我将 SessionsHelper 与我的 SessionsController 一起使用,并且在类之外有我的 include 语句:

include SessionsHelper

class SessionsController < ApplicationController
  def new
  end
  ...
  ...
  ...
end

通过在类中移动 include 语句:

class SessionsController < ApplicationController
  include SessionsHelper

  def new
  end
  ...
  ...
  ...
end

我所有的测试都开始通过了。虽然我的测试在 class 块之外使用 include 语句失败,但实际功能似乎工作正常。我可以登录/注销,cookie 被存储了正确的信息,并且我在服务器控制台中没有看到任何错误。

于 2012-07-14T17:44:05.910 回答