Как #let файл JSON в RSpec на Rails - PullRequest
       23

Как #let файл JSON в RSpec на Rails

0 голосов
/ 11 сентября 2018

EDIT:

Решение, похоже, начинается с describe KayNein::Twitter do вместо RSpec.describe KayNein::Twitter do.

Почему это так?

Рельсы 5.2.1 Ruby 2.5.1p57 (версия 20130-03-29 63029) [x86_64-linux]

Оригинальный вопрос

У меня есть класс, который инициализируется с помощью файла JSON:

module KayNein
  class Twitter < Handler

    def initialize(json_file)
      @website_hash = JSON.parse(json_file)
    end

И я пытаюсь написать RSpec:

RSpec.describe KayNein::Twitter do
  let (:json_file) {File.read(PATH_TO_FILE)}
  context "Initialized" do
    subject = KayNein::Twitter.new(json_file)
  end
end

Но RSpec выдает мне эту ошибку:

An error occurred while loading ./spec/app/kay_nein/sites/twitter_spec.rb.
Failure/Error: subject = KayNein::Twitter.new(json_file)
  `json_file` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run
 in the scope of an example (e.g. `before`, `let`, etc).
# ./spec/app/kay_nein/sites/twitter_spec.rb:8:in `block (2 levels) in <top (required)>'
# ./spec/app/kay_nein/sites/twitter_spec.rb:7:in `block in <top (required)>'
# ./spec/app/kay_nein/sites/twitter_spec.rb:5:in `<top (required)>'

Что я делаю не так?

Даже это дает мне ошибку, так что это не имеет ничего общего с файлом:

RSpec.describe KayNein::Twitter do
  let (:json_file) {"Hello world"}
  context "Initialized" do
    subject = KayNein::Twitter.new(json_file)
  end
end 

Ответы [ 3 ]

0 голосов
/ 11 сентября 2018
We have two ways to DRY up tests (before and let) that share an intersecting purpose, to create variables that are common across tests. For common variable instantiation, the Ruby community prefers let, and while before is often used to perform actions common across tests.

when you use the context you can initialize the let inside the context block like this, will work

describe KayNein::Twitter do
  context "Initialized" do
    let (:json_file) {File.read(PATH_TO_FILE)}
    subject = KayNein::Twitter.new(json_file)
  end
end

otherwise if you don't want to use context, can try this way

describe KayNein::Twitter do
let (:json_file) {File.read(PATH_TO_FILE)}
  it "Initialized" do
    subject = KayNein::Twitter.new(json_file)
  end
end
0 голосов
/ 11 сентября 2018

Вы можете думать о let как определяющих средства доступа.И эти средства доступа доступны только внутри примеров блоков it или specify.

Вы пытаетесь использовать json_file (определено в let) внутри context.И это именно то, что пытается сообщить вам сообщение об ошибке:

json_file недоступно в группе примеров (например, блок describe или context).Он доступен только из отдельных примеров (например, it блоков) или из конструкций, которые выполняются в области действия примера (например, before, let и т. Д.).

Вы можетеисправьте это так:

RSpec.describe KayNein::Twitter do
  let (:json_file) {File.read(PATH_TO_FILE)}
  context "Initialized" do
    specify do # it instead of specify also works
     subject = KayNein::Twitter.new(json_file)
     expect(subject).not_to be_nil # this is just an example, not needed to 
                                   # get rid of the issue
    end
  end
end

или даже лучше - определите объект вне примера блока (для повторного использования и т. д.) следующим образом:

RSpec.describe KayNein::Twitter do
  let (:json_file) {File.read(PATH_TO_FILE)}
  subject { KayNein::Twitter.new(json_file) }
  context "Initialized" do
    specify do # it instead of specify also works
     expect(subject).not_to be_nil # this is just an example, not needed to 
                                   # get rid of the issue
    end
  end
end
0 голосов
/ 11 сентября 2018

Можете ли вы попробовать что-то подобное?

let(:file) { File.read(File.join('spec', 'fixtures', 'public', filename)) }

describe "File" do
  it "should be a file" do
    expect(file).to be_a File
  end

  it "should initialize and read the contents"
    initialize_file = KayNein::Twitter.new(file)
    expect(response.body["key"]).to eq(..)
  end
end
...