gpt4 book ai didi

ruby-on-rails - 运行时错误 : #let or #subject called without a block

转载 作者:行者123 更新时间:2023-12-04 23:40:18 30 4
gpt4 key购买 nike

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

  its(:user) { should == user }

我试图这样做:
  expect(subject.user).to eq(user)

但是得到一个错误

RuntimeError: #let or #subject called without a block



如果您需要,这是我的完整 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

最佳答案

是的,你必须遵循一个过时的版本,因为 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让您使用 its 的 gem使用当前版本的 RSpec 的语法。
# with rspec-its
its(:user) { is_expected.to eq user }
# or
its(:user) { should eq user }

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

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

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

关于ruby-on-rails - 运行时错误 : #let or #subject called without a block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573939/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com