【问题标题】:rspec: undefined method 'latest'rspec:未定义的方法“最新”
【发布时间】:2014-03-25 12:36:50
【问题描述】:

我正在模型中测试一种方法。叫last_photo,我填了数据库的数据,尝试返回第一个元素,结果报错udefined method 'latest'。会是什么呢?我该如何解决?

方法latest这个: 范围:最新,-> { order('created_at DESC') }

def last_photo
  @last_photo ||= user_updates.latest.where("photo_front IS NOT NULL and photo_front != ''").first.try(:photo_front)
end

context "instance method" do
  let(:user) { create :user }

  context "last photo" do
    before { create_list(:user_update, 3, user: user) }
    let(:user_updates){ UserUpdate.all }

    describe "#last_photo" do
      subject { user.last_photo }

      it { should eq user_updates.latest.first.photo_front }
    end

    describe "#last_photo_side" do
      subject { user.last_photo_side }

      it { should eq user_updates.latest.first.photo_side}
    end
  end
end

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec2 rspec-rails


    【解决方案1】:

    我打赌UserUpdate.all 返回一个数组。所以你不能在上面链接范围。

    替换为:

    let(:user_updates){ UserUpdate.scoped }
    

    【讨论】:

    • 好的,谢谢。我有另一个问题。这里如何使用where 方法?
    • 我不明白你的意思
    • where("photo_front IS NOT NULL and photo_front != ''") 在测试中使用?
    • 我会说:让它成为一个范围并在你的规范中使用范围
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多