【问题标题】:Refactoring rspec with let用 let 重构 rspec
【发布时间】:2013-11-30 04:33:29
【问题描述】:

我正在关注 Michael Hartl 的 Ruby on Rails 教程。 如何使用let 重构下面的代码而不是使用实例变量?

describe User do    

  before do
    @user = User.new(name: "Example User", email: "user@example.com")
  end    

  subject { @user }    

  it { should respond_to(:name) }
  it { should respond_to(:email) }    

  it { should be_valid }    

  describe "when name is not present" do
    before { @user.name = " " }
    it { should_not be_valid }
  end
end

我尝试自己重构代码但失败了。

describe User do
  let(:user) { User.new(name: "Example User", email:"foo@example.com") }    

  subject { user }    

  it { should respond_to(:name) }
  it { should respond_to(:email) }  

  it { should be_valid }    

  describe "when name is not present" do
    # ???
    let(:name) { " " } 
    it { should_not be_valid }
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec railstutorial.org


    【解决方案1】:

    对于“当名称不存在”示例组,这就足够了:

    describe "when name is not present" do
      before { subject.name = '' }
      it { should_not be_valid }
    end
    

    从您单独发布的代码来看,将:name 设置为let() 没有任何附加价值。

    【讨论】:

    • 哇,谢谢!我刚刚找到了方法:before { user.name = " " },但不知道我可以使用subject.name,谢谢!:)
    • 是的,使用subject 更有意义,因为它专门用于should_not be_valid 中的测试。 :-)
    猜你喜欢
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多