【问题标题】:Access to the other models访问其他模型
【发布时间】:2013-03-03 15:28:55
【问题描述】:

我正在尝试让它工作。我进行了适当的关联,但仍然失败。看看我的代码。

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
  attr_accessible :content

  before_create :format_content

  validates :content, presence:true, length: {minimum:21}

  def format_content
    profil = self.user.profile
    if profil.gender == "Mężczyzna"
      "Wiadomość od spottera: #{self.content}"
    elsif profil.gender == "Kobieta"
      "Wiadomość od spotterki: #{self.content}"
    end
  end
end

post_spec.rb

describe "Properly formats content" do
    let(:user) {FactoryGirl.create(:user)}
    let!(:poscik) {FactoryGirl.create(:post) }
    before(:each) {user.create_profile!(gender: "Kobieta", email: "donatella@dostojnie.pl")}

rspec_failures

Post creation valid should have content Failure/Error: poscik = user.posts.create(content: "Weird #{"a"*25}") NoMethodError: undefined method `gender' for nil:NilClass

如何正确访问模型中的其他类以及为什么找不到我的方法?我理解错误消息 - 它说我的配置文件类未定义


用户工厂

FactoryGirl.define do
  factory :user do
    sequence(:email) {|i|"maestro#{i}@dot.pl"}
    password "kravmaga1290"
    association :profile, factory: :profile, strategy: :build
  end
end

【问题讨论】:

  • 代码异味:profil.gender == "Mężczyzna",不是Post的问题,创建专用方法
  • 什么类型的专用方法?
  • 在个人资料中:def male?; gender == "Mężczyzna"; end。在帖子中:if profile.male?
  • 其他代码气味:format_content 我猜是在视图中使用。所以它应该存在于演示者中,而不是模型中
  • 这很有帮助,谢谢

标签: ruby-on-rails testing rspec models


【解决方案1】:

您似乎还没有创建类Profile 的对象。我认为它是在抱怨你打电话来获取 profile.gender 的 nil 类。

尝试在工厂中添加如下内容:

Factory.define :user do |f|
  f.after_build do |user|
    user.profile ||= Factory.build(:profile, :user => user)
  end
end

当然,您还必须定义配置文件工厂。 让我知道这是否有帮助

【讨论】:

    【解决方案2】:

    当您在 Post 模型中执行 self.user.profile 时,它找到的用户没有与之关联的个人资料。您应该能够在您的 FactoryGirl 定义中为 User 类设置关联。

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2015-06-01
      • 2010-12-02
      • 2016-12-16
      相关资源
      最近更新 更多