Aydar Omurbekov
Aydar Omurbekov

Reputation: 2117

Factory girl and rspec unit testing

I am using factory_girl_rails and rspec and run into trouble, raises the folloing error

   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.

It is my code in spec.rb file

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

The factory_girl factories

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

Upvotes: 1

Views: 1143

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29399

Since I think it's helpful to understand why you received the error you received, here's an explanation:

  • You're statement had four expressions separated by spaces: website_link.external, should, be and false
  • Ruby evaluates these from right to left
  • false is trivial
  • be is interpreted as a method call with false as an argument
  • should is interpreted as a method with the result of be as an argument.
  • should is interpreted relative to subject, since the method wasn't sent to a specific object
  • Given the error you received, subject was either explicitly set to be WebsiteLink or that was the argument to describe for a parent of the example and thus the implicit subject
  • website_link.external never got evaluated because the error occurred prior to that point

Upvotes: 5

Miguelgraz
Miguelgraz

Reputation: 4436

You forgot to use the dot.

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 (note the dot between external and should)
end

Give it a try.

Upvotes: 1

Related Questions