【问题标题】:RuntimeError: #let or #subject called without a blockRuntimeError: #let 或 #subject 调用时没有块
【发布时间】:2016-09-19 21:29:32
【问题描述】:

这是我的第一个 rspec 测试 我正在使用 Hurtl 的教程,并认为它已经过时了。 我想更改这一行,因为its 不再是 rspec 的一部分:

  its(:user) { should == user }

我尝试过这样做:

  expect(subject.user).to eq(user)

但是报错

RuntimeError: #let 或 #subject 调用时没有块

如果您需要,这是我的完整 rspec 测试:

require 'spec_helper'
require "rails_helper" 

describe Question do

  let(:user) { FactoryGirl.create(:user) }
  before { @question = user.questions.build(content: "Lorem ipsum") }

  subject { @question }

  it { should respond_to(:body) }
  it { should respond_to(:title) }
  it { should respond_to(:user_id) }
  it { should respond_to(:user) }

  expect(subject.user).to eq(user)
  its(:user) { should == user }

  it { should be_valid }

  describe "accessible attributes" do
    it "should not allow access to user_id" do
      expect do
        Question.new(user_id: user.id)
      end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end
  end

  describe "when user_id is not present" do
    before { @question.user_id = nil }
    it { should_not be_valid }
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    是的,因为 M. Hartl 的 Railstutorial 书现在使用 Minitest 而不是 RSpec,所以您必须遵循过时的版本。

    expect(subject.user).to eq(user)
    

    不起作用,因为您调用 subject 而不将其包装在 it 块中。

    你可以改写成:

    it "should be associated with the right user" do
      expect(subject.user).to eq(user)
    end
    

    或者您可以使用 rspec-its gem,它允许您在当前版本的 RSpec 中使用 its 语法。

    # with rspec-its
    its(:user) { is_expected.to eq user }
    # or
    its(:user) { should eq user }
    

    但它仍然不是一个特别有价值的测试,因为您只是在测试测试本身而不是应用程序的行为。

    此外,此规范适用于旧版本(3.5 之前)的导轨,其中质量分配保护在模型级别完成。

    您可以在https://www.railstutorial.org/ 找到当前版本的 Rails Turorial 书籍。

    【讨论】:

      【解决方案2】:

      您不能将its(:user) { should == user } 直接翻译成expect(subject.user).to eq(user)。你必须用it 块包围它

      it 'has a matchting user' do
        expect(subject.user).to eq(user)
      end
      

      【讨论】:

      • 忘记it 块是那些可能让某人发疯的微妙错误之一 - 感谢您在此处指出显而易见的事情!
      猜你喜欢
      • 1970-01-01
      • 2019-07-08
      • 2019-11-04
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多