如何在Rails上的RSpec中#let一个JSON文件

问题描述 投票:0回答:3

编辑:

解决方案似乎从describe KayNein::Twitter do而不是RSpec.describe KayNein::Twitter do开始。

为什么会这样?

Rails 5.2.1 Ruby 2.5.1p57(2018-03-29 Revision 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 
ruby-on-rails json rspec let
3个回答
© www.soinside.com 2019 - 2024. All rights reserved.