【问题标题】:RSpec::Expectations::ExpectationNotMetError in cucumber routing issue黄瓜路由问题中的 RSpec::Expectations::ExpectationNotMetError
【发布时间】:2013-02-28 07:42:22
【问题描述】:

我开始通过黄瓜研究 BDD。 (使用 Rails-3,gem 'cucumber-rails')
我想在成功登录后重定向到用户个人资料页面 (/users/id)。
我在控制器中定义为 (redirect_to user_path(@user)) 和我在 cucumber 中定义的相同的东西 (page.current_path.should == user_path(@user))

在我的 step_definition 中

Given /^a user visits the signin page$/ do
  visit signin_path
end

When /^he log in as "(.*)\/(.*)"$/ do |email, password|
  @email = email
  fill_in "email", with: email
  fill_in "password", with: password
  click_button "Login"
end

Then /^he should see a signin link$/ do
  page.should have_link('Sign in', href: signin_path)
end

Then /^he should see his profile page$/ do
  @user = User.where("email = ?", @email)
  page.current_path.should == user_path(@user)
end

在我的控制器中

class SessionsController < ApplicationController

 def create
  @user = User.find_by_email(params[:session][:email].downcase)
  if @user && @user.authenticate(params[:session][:password])
   sign_in @user      
   redirect_to user_path(@user)               
  else
   flash.now[:error] = 'Invalid email/password combination'
   render 'new'
  end
 end
end

现在在运行 cucumber 时,我收到此错误:

expected: "/users/%23%3CActiveRecord::Relation:0x000000062fbec0%3E"
       got: "/users/4" (using ==) (RSpec::Expectations::ExpectationNotMetError)

在我的 features/support/env.rb 中:

require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/rails'
require 'rspec/expectations'

请回答我哪里做错了。

【问题讨论】:

    标签: ruby-on-rails-3 cucumber capybara bdd rspec-expectations


    【解决方案1】:

    您的步骤定义中的这段代码是问题所在:

    Then /^he should see his profile page$/ do
      @user = User.where("email = ?", @email)
      page.current_path.should == user_path(@user)
    end
    

    User.where 将始终返回一个关系,即使结果只有一条用户记录,因此您的错误消息中包含 ActiveRecord::Relation 部分。

    如果您确定只会返回一个用户,您可以将其换成User.find_by_email(@email)User.where(:email =&gt; @email).first 之类的东西,以获得单个用户实例。

    【讨论】:

    • thnx Sevenseacat .....它解决了我的问题。并且User.where will always return a relation, even if the result is only one User record, hence the ActiveRecord::Relation part of your error message 行将来对我也将更有用。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多