undefined local variable or method for #<rspec +="" rspec="" 3.5=""

时间:2016-09-10 15:24:25

标签: rspec

="" Stackers,

I am stuck on an error that I keep getting when running this spec in RSPEC. I am using:

rspec-core (3.5.3) rspec-support (~> 3.5.0) rspec-expectations (3.5.0)

Now here is the spec that I am using:

require 'rails_helper'

RSpec.describe Service, type: :model do
  it "has a valid factory" do
    expect(service).to be_valid
  end
end

This is the factory with factory girl:

FactoryGirl.define do
  factory :service do
    name        { Faker::Lorem.word }
    description { Faker::Lorem.paragraphs(5) }
  end
end

I have a service model "service.rb" and the content is rather simple:

class Service < ApplicationRecord
  validates :name, presence: true
  validates :description, presence: true
end

And finally this is the error that I keep getting:

Failures:

  1) Service has a valid factory
     Failure/Error: expect(service).to be_valid

     NameError:
       undefined local variable or method `service' for #<RSpec::ExampleGroups::Service:0x007fa4ba80bea0>
     # ./spec/models/service_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.02976 seconds (files took 1.52 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/models/service_spec.rb:4 # Service has a valid factory

1 个答案:

答案 0 :(得分:3)

可能,下面你需要写的东西。您需要通过Factory初始化服务实例以在spec文件中使用。

foreach (M1t4LicensesInfo obj in DataAfterSearch)
     {
         data += "<tr><td>" + SearchLicenseType.Items[obj.LicenseType] + "</td><td>" + SearchLicenseExtractedFrom.Items[int.Parse(obj.PublishingDesk)] +
                 "</td><td>" + obj.PublishingDate + "</td><td>" + obj.LicenseNumber + "</td><td>" + obj.PublishingDate+;   
        string Edit ="</td><td>"+"<asp:ImageButton  runat=\"server\" ImageUrl=\"~/Images/Edit.png\" />"+ "</td></tr>";                        
    data+=Edit 
}

更好的方法是在上下文之外构建工厂实例,并在多个测试中使用相同的实例。

 RSpec.describe Service, type: :model do
  it "has a valid factory" do
    service = FactoryGirl.create :service
    expect(service).to be_valid
  end
end