Rspec测试属于并且有许多

时间:2012-11-15 01:06:11

标签: ruby-on-rails ruby ruby-on-rails-3 rspec associations

我正在运行一个rspec测试,以确保两个模型相互关联has_manybelongs_to。以下是我的测试。

describe "testing for has many links" do
  before do
    @post = Post.new(day: "Day 1", content: "Test")
    @link = Link.new(post_id: @post.id, title: "google", url: "google.com")
  end

  it "in the post model" do
    @post.links.first.url.should == "google.com"
  end
end

测试告诉我url是一种未定义的方法。我的考试有什么问题?或者我只是错过了一些基本的东西。

Post

的模型文件
has_many :links

Link

的模型文件
belongs_to :post

最重要的是,链接模型具有属性post_id

2 个答案:

答案 0 :(得分:15)

您需要保存这两个模型以验证此关系,同样,您可以使用shoulda gem。

代码如下:

describe Link do
  it { should belong_to(:post) }
end

describe Post do
  it { should have_many(:links) }
end

答案 1 :(得分:1)

您需要将link分配给post否则,如果执行@post.links,您将获得一个空数组([]),[].first返回{ {1}}。然后尝试nil,然后你得到 url是nil.url 的未定义方法。

NilClass
相关问题