10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rspecでbindingを使って変数の中身を調べる方法

Last updated at Posted at 2018-11-08

##起こった問題
binding.pryを使えばどこでも停止させることができるが、変数の中身とか見れなくて困った。


RSpec.describe Model, :type => :model do
  describe "validations" do
    before do
      @user = User.new(name: "hoge")
    end
    binding.pry #追加
    it "valid?" 
      expect(@user).to be_invalid
    end
  end
end

> @user.name
RSpec::Core::ExampleGroup::WrongScopeError: `user` is not available on an example group (e.g. a `describe` or `context` block). ......

結論から言えば、itの中であれば参照することができる

##itの中で使う

実際に見てみましょう。


RSpec.describe Model, :type => :model do
  describe "validations" do
    before do
      @user = User.new(name: "hoge")
    end
    it "valid?" 
      @user.name = nil
      binding.pry #追加
      expect(@user).to be_invalid
    end
  end
end
> @user.name
"hoge"

Userインスタンスのnameが変更されているのも確認できてます。

もちろん、FactoryGirlを使った場合も同様に参照可能。


RSpec.describe Model, :type => :model do
  describe "validations" do
    let!(:user) { User.new }
    it "valid?" 
      binding.pry #追加
      expect(user).to be_invalid
    end
  end
end
> user.name
"hoge"
10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?