Ошибка определения метода с неопределенным именем в Rails3 - PullRequest
1 голос
/ 29 октября 2010

Работая с RailsTutorial Майкла Хартла, натолкнулся на следующую ошибку - хотя я следовал всему до 'T'.

1) UsersController GET 'index' for signed-in users should have an element for each user
Failure/Error: response.should have_selector("li", :content => user.name)
undefined method `name' for #<Array:0x000001032c07c8>

Кто-нибудь еще получил подобную ошибку и знает, как ее исправить?

Я в главе 10.

Кстати, когда я пробую страницу, она делает то, что должна.Просто тест не пройден в RSpec.

FYI, вот соответствующий тестовый код из users_controller_spec.rb

require 'spec_helper'

describe UsersController do
    render_views

    describe "GET 'index'" do

        describe "for non-signed-in users" do
            it "should deny access" do 
                get :index
                response.should redirect_to(signin_path)
                flash[:notice].should =~ /sign in/i
            end
        end

        describe "for signed-in users" do 

            before(:each) do 
                @user = test_sign_in(Factory(:user))
                second = Factory(:user, :email => "another@example.com")
                third = Factory(:user, :email => "another@example.net")

                @users = [@user, second, third]
            end

            it "should be successful" do 
                get :index
                response.should be_success
            end

            it "should have the right title" do 
                get :index
                response.should have_selector("title", :content => "All users")
            end

            it "should have an element for each user" do
                get :index
                @users.each do |user|
                    response.should have_selector("li", :content => user.name)
                end
            end
        end
    end

Мой файл spec / spec_helper.rb выглядит следующим образом:

require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However, 
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in 
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear

    def test_sign_in(user)
        controller.sign_in(user)
    end

    def integration_sign_in(user)
        visit signin_path
        fill_in :email,             :with => user.email
        fill_in :password,          :with => user.password 
        click_button
    end    
  end
end

Spork.each_run do
end

Ответы [ 2 ]

0 голосов
/ 31 октября 2010

Я решил эту проблему, и ответ можно найти на railstutorial официальных форумах.

0 голосов
/ 29 октября 2010

Похоже, ваш test_sign_in метод возвращает экземпляр массива, а не объект User. Вы явно возвращаете пользовательский объект в методе test_sign_in ? Если нет, взгляните на последнюю строку, которая выполняется в этом методе, у меня есть ощущение, что результатом является массив.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...