在rails中开始使用rspec

时间:2014-05-26 01:14:49

标签: ruby-on-rails ruby unit-testing testing rspec

我正在尝试为Student课程编写规范。到目前为止它很简单;它只有一个名字和一个姓氏。我需要确保这两个字段都不是空白的。到目前为止我有这个:

describe Student do
    context "is valid" do
            before do
              @student = Student.new
            end

            it "should have a first name" do
              expect(student).not_to be_valid
            end

            it "should have a last name" do
              expect(student).not_to be_valid
            end
        end
    end

当我运行测试时,它表示student对于它们都是未定义的局部变量。为什么之前不起作用?

1 个答案:

答案 0 :(得分:0)

因为@student是一个实例变量,而RSpec不会自动创建属性。如果您想使用student代替@student,请使用let

describe Student do
  context "is valid" do
    let(:student) { Student.new }

    it "should have a first name" do
      expect(student).not_to be_valid
    end

    it "should have a last name" do
      expect(student).not_to be_valid
    end
  end 
end

相关文档:http://www.betterspecs.org/#let

相关问题