ruby-on-rails - Michael Hartl 教程第 11 章中的 "undefined method ` find_by '"

标签 ruby-on-rails ruby testing rspec

我遇到了这 2 个错误,但我不确定如何修复它们。我一直遇到的一个问题是教程的新版本和旧版本之间的差异(rails 4 和 3.2 之间的差异)。

我的规范是:

ruby 版本:1.9.2p320

Rails 版本:3.2.13

Rspec: 2.11.1

计算机:Macbook Pro OS X Mountain Lion

错误

  1) User following and unfollowing 
     Failure/Error: before { @user.unfollow!(other_user) }
     NoMethodError:
       undefined method `find_by' for []:ActiveRecord::Relation
     # ./app/models/user.rb:36:in `unfollow!'
     # ./spec/models/user_spec.rb:47:in `block (4 levels) in <top (required)>'

  2) User following and unfollowing followed_users 
     Failure/Error: before { @user.unfollow!(other_user) }
     NoMethodError:
       undefined method `find_by' for []:ActiveRecord::Relation
     # ./app/models/user.rb:36:in `unfollow!'
     # ./spec/models/user_spec.rb:47:in `block (4 levels) in <top (required)>'

用户.rb

  def following?(other_user)
    relationships.where(followed_id: other_user.id).first
  end

  def follow!(other_user)
    relationships.create!(followed_id: other_user.id)
  end

  def unfollow!(other_user)
    relationships.find_by(followed_id: other_user.id).destroy!
  end

user_spec.rb

describe "following" do
    let(:other_user) { FactoryGirl.create(:user) }
    before do
      @user.save
      @user.follow!(other_user)
    end

    it { should be_following(other_user) }
    its(:followed_users) { should include(other_user) }

    describe "followed users" do 
      subject { other_user }
      its(:followers) {should include(@user) } 
    end

    describe "and unfollowing" do
      before { @user.unfollow!(other_user) }

      it {should_not be_following(other_user) }
      its(:followed_users) {should_not include(other_user) }
    end
  end

最佳答案

find_by 因为你正在使用它,在 Rails 3 中不存在。Rails 3 为此使用了 method_missing,所以使用 find_by_followed_id会工作。

我推荐使用 Hartl 的 Rails 3 tutorial .

关于ruby-on-rails - Michael Hartl 教程第 11 章中的 "undefined method ` find_by '",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18217066/

相关文章:

javascript - 断言 testcafe 中是否存在带有特定文本的 td DOM

ruby-on-rails - 在 Rails API 中针对测试环境运行 Pact

ruby-on-rails - 用户、公司、介绍人之间的关系模型

ruby - 什么不能从 ruby​​ 中的对象访问类变量?

java - 从一个测试调用方法时的 junit 测试

ruby-on-rails - Rails 属于依赖破坏

javascript - 如何将 Ruby 对象传递给 Javascript?

ruby-on-rails - 如何创建这个 Ruby on Rails 表单?

ruby-on-rails - 图像的动态CSS

ruby-on-rails - Httparty::Response 和 try(:parsed_response) 奇怪的行为