工厂女孩和rspec单元测试

Ayd*_*kov 1 rspec ruby-on-rails factory-bot

我正在使用factory_girl_rails和rspec并遇到麻烦,引发了以下错误

   1) WebsiteLink when link is external
         Failure/Error: website_link.external should be false

           expected #<FalseClass:0> => false
                got #<WebsiteLink:100584240> => #<WebsiteLink id: nil, website_id: nil, link: nil, external: nil, checked: nil, click_count: nil, transition_count: nil, created_at: nil, updated_at: nil, link_description: nil>

           Compared using equal?, which compares object identity,
           but expected and actual are not the same object. Use
           `expect(actual).to eq(expected)` if you don't care about
           object identity in this example.
Run Code Online (Sandbox Code Playgroud)

这是我在spec.rb文件中的代码

it "when link is external" do
    website = FactoryGirl.create(:website,site_address: "www.socpost.ru")
    website_link = FactoryGirl.create(:website_link, link: "www.google.com", website: website)
    website_link.external should be true
  end
Run Code Online (Sandbox Code Playgroud)

factory_girl工厂

FactoryGirl.define do
 factory :website do
    sequence(:site_name){ |i| "Facebook#{i}" }
    sequence(:site_address){ |i| "www.facebook_#{i}.com" }
    sequence(:website_key){ |i| (1234567 + i).to_s }
  end
  factory :website_link do
    sequence(:link){ |i| "www.facebook.com/test_#{i}" }
    external false
    checked false
    click_count 1
    transition_count 1
    link_description "Hello"
    website
  end
end
Run Code Online (Sandbox Code Playgroud)

Pet*_*vin 5

既然我认为理解你收到错误的原因是有帮助的,这里有一个解释:

  • 你在发言中四个表达式用空格分隔:website_link.external,should,befalse
  • Ruby从右到左评估这些
  • false 是微不足道的
  • be被解释为带有false参数的方法调用
  • should被解释为具有be作为参数的结果的方法.
  • should是相对于解释subject,因为该方法未发送到特定对象
  • 鉴于您收到的错误,subject要么显式设置为WebsiteLink或者是describe该示例的父级的参数,因此是隐式的subject
  • website_link.external 从未得到评估,因为错误发生在该点之前