gpt4 book ai didi

ruby-on-rails - 使用 RSpec 测试多态关联

转载 作者:行者123 更新时间:2023-12-04 07:37:41 24 4
gpt4 key购买 nike

我正在为多态关联编写 RSpec 代码。我有两个测试想法

  • 使用Factory Girl建立多态关联
  • 使用 rails 方法构建多态关联。

  • 下面是我写的代码片段(相关代码在底部):

    1) link_spec.rb,创建与 FactoryGirl 的关联。
    describe "Book links" do
    let(:book) { FactoryGirl.create(:book) }
    let(:book_link) { FactoryGirl.create(:book_link, linkable: book) }

    subject{ book_link }

    it { should be_valid }

    it { should respond_to(:url) }
    it { should respond_to(:linkable) }
    its(:linkable) { should eq book }
    end

    2)link_spec.rb,通过rails方法创建关联。
    describe "Book links" do
    let(:book) { FactoryGirl.create(:book) }
    let(:link) { book.links.create(url: "http://example.com") }

    subject { link }

    it { should be_valid }

    it { should respond_to(:url) }
    it { should respond_to(:linkable) }
    its(:linkable) { should eq book }
    end

    感觉后者测试比前者好,但没信心。
    或者它们彼此等效?

    书.rb
    class Book < ActiveRecord::Base
    has_many :links, as: :linkable
    end

    链接文件
    class Link < ActiveRecord::Base
    belongs_to :linkable, polymorphic: true
    end

    工厂.rb
    factory :book do
    title "Foo bar"
    author "John"
    end

    factory :book_link, class: "Link" do
    association :linkable, factory: :book
    url "http://examle.com"
    end

    最佳答案

    I feel the latter is testing better than the former, but have no confidence.



    如果您打算隐含地询问哪个“更好”,那么该问题不适合 StackOverflow。

    Or are they equivalent to each other?



    从某种意义上说,设置结果相同 Link对象正在创建,我会说是的,它们是等效的。但是,第二个测试了为 Book 设置的关联辅助方法。 ,您可能会觉得这是可取的。

    关于ruby-on-rails - 使用 RSpec 测试多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21748726/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com