Michael Hartl教程第10章中的“未定义方法有效吗?”

时间:2013-08-10 19:27:14

标签: ruby-on-rails ruby rspec

我在micropost_spec。rb文件中为我的代码收到以下3个错误。我该如何修理它们?我认为我正在完全按照教程进行操作,但是对于不同版本的Rails可能存在问题。

Ruby版本:1.9.2p320

Rails版本:3.2.13

Rspec:2.11.1

计算机:Macbook pro OS X Mountain Lion

错误

1) Micropost when user_id is not present 
   Failure/Error: it { User.should_not be_valid }
   NoMethodError:
     undefined method `valid?' for #
   # ./spec/models/micropost_spec.rb:19:in `block (3 levels) in '

2) Micropost with blank content 
   Failure/Error: it { User.should_not be_valid}
   NoMethodError:
     undefined method `valid?' for #
   # ./spec/models/micropost_spec.rb:24:in `block (3 levels) in '

3) Micropost when content is too long 
   Failure/Error: it { User.should_not be_valid }
   NoMethodError:
     undefined method `valid?' for #
   # ./spec/models/micropost_spec.rb:29:in `block (3 levels) in '

micropost_spec.rb

require 'spec_helper'

describe Micropost do

  let(:user) { FactoryGirl.create(:user) }
  before { @micropost = user.microposts.build(content: "Lorem ipsum") }

  subject { @micropost }

  it { should respond_to(:content) }
  it { should respond_to(:user_id) }
  it { should respond_to(:user) }
  its(:user) { should eq user }

  it { should be_valid }

  describe "when user_id is not present" do
    before { @micropost.user_id = nil }
    it { should_not be_valid }
  end

  describe "with blank content" do
    before { @micropost = " "}
    it { should_not be_valid}
  end

  describe "when content is too long" do
    before { @micropost = "a" * 141 }
    it { should_not be_valid }
  end
end

1 个答案:

答案 0 :(得分:0)

您收到的错误消息与您共享的spec文件不匹配。错误消息显示User.should ....,而您的规范有隐含主题。该错误反映出您在课程valid?而不是预期的User上间接调用@micropost

相关问题