【问题标题】:Rails Rspec error "undefined method" (railsturoial Chapter 10)Rails Rspec 错误“未定义的方法”(railstuial 第 10 章)
【发布时间】:2013-02-04 01:17:01
【问题描述】:

我正在阅读 Michael Hartl 的无价教程,但遇到了一些 Rspec 错误。我已经仔细检查了所有内容,但似乎我仍然缺少一些东西。错误消息如下所示。

最困扰我的是在生成 Microposts 模型时,我不小心在其中一个选项中打错了字,所以我在再次生成模型之前使用 rails destroy model Microposts 撤消了生成命令。我想知道这是否与我看到的错误有关。

我真的希望尽快完成本教程,以便继续构建自己的 Web 应用程序。任何帮助将不胜感激。

这是我的代码的样子。

micropost_pages_spec.rb

require 'spec_helper'

describe "MicropostPages" do
    subject {page}
    let(:user) {FactoryGirl.create(:user)}
        before {sign_in user}
        describe "micropost creation" do
            before {visit root_path}

            describe "with invalid information" do
                it "should not create a micropost" do
                expect {click_button "Post"}.not_to change(Micropost, :count)               
            end

            describe "error messages" do
                before {click_button "Post"}
                it {should have_content('error')}
            end
        end
    end
end

microposts_controller.rb

class MicropostsController < ApplicationController
    before_filter :signed_in_user, only: [:create, :destroy]

    def create
        @micropost = current_user.micropost.build(params[:micropost])
        if @micropost.save
            flash[:success] = "Micropost created!"
            redirect_to root_path
        else
            render 'static_pages/home'
        end
    end

    def destroy
    end
end

static_pages_controller.rb

class StaticPagesController < ApplicationController
  def home
    @micropost = current_user.microposts.build if signed_in?
  end

  def help
  end

  def about
  end

  def contact
  end

end

user.rb(用户模型)

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation
  has_secure_password
  has_many :microposts, dependent: :destroy

  before_save {self.email.downcase!}
  before_save :create_remember_token

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :name,  presence: true, length: {maximum: 50}
  validates :email, presence: true, format: {with: VALID_EMAIL_REGEX},
                    uniqueness: {case_sensitive: false}
  validates :password, presence: true, length: {minimum: 6}
  validates :password_confirmation, presence: true

  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end
end

【问题讨论】:

    标签: ruby-on-rails rspec railstutorial.org


    【解决方案1】:

    错误在于这一行:

    @micropost = current_user.micropost.build(params[:micropost])
    

    应该是:

    @micropost = current_user.microposts.build(params[:micropost])
    

    你使用的是micropost,而你应该使用microposts

    【讨论】:

    • 哈哈哇非常感谢!一旦计时器用完,将设置为答案。
    • @jkface:定时器已经用完了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2013-05-23
    相关资源
    最近更新 更多